Add test for benchmarking NetworkStatsCollection

Add a test for benchmarking NetworkStatsCollection.
The test use data that generated from real user dataset which
has many uid records and agreed to share the dataset for testing
purpose.

Test: atest ConnectivityBenchmarkTests
Bug: 269409485

Change-Id: I8981bfc9f65636897c6fc735cda5353b448a0db2
diff --git a/tests/benchmark/Android.bp b/tests/benchmark/Android.bp
new file mode 100644
index 0000000..cb01732
--- /dev/null
+++ b/tests/benchmark/Android.bp
@@ -0,0 +1,41 @@
+//
+// Copyright (C) 2023 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 {
+    // See: http://go/android-license-faq
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test {
+    name: "ConnectivityBenchmarkTests",
+    defaults: [
+        "framework-connectivity-internal-test-defaults",
+    ],
+    platform_apis: true,
+    srcs: [
+        "src/**/*.kt",
+        "src/**/*.aidl",
+    ],
+    static_libs: [
+        "androidx.test.rules",
+        "net-tests-utils",
+        "service-connectivity-pre-jarjar",
+        "service-connectivity-tiramisu-pre-jarjar",
+    ],
+    test_suites: ["device-tests"],
+    jarjar_rules: ":connectivity-jarjar-rules",
+}
+
diff --git a/tests/benchmark/AndroidManifest.xml b/tests/benchmark/AndroidManifest.xml
new file mode 100644
index 0000000..bd2fce5
--- /dev/null
+++ b/tests/benchmark/AndroidManifest.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2023 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.android.server.connectivity.benchmarktests">
+    <application>
+        <uses-library android:name="android.test.runner" />
+    </application>
+
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
+         android:targetPackage="com.android.server.connectivity.benchmarktests"
+         android:label="Connectivity Benchmark Tests" />
+</manifest>
diff --git a/tests/benchmark/OWNERS b/tests/benchmark/OWNERS
new file mode 100644
index 0000000..3101da5
--- /dev/null
+++ b/tests/benchmark/OWNERS
@@ -0,0 +1,2 @@
+# Bug template url: http://b/new?component=31808
+# TODO: move bug template config to common owners file once b/226427845 is resolved
\ No newline at end of file
diff --git a/tests/benchmark/res/raw/netstats-many-uids-zip b/tests/benchmark/res/raw/netstats-many-uids-zip
new file mode 100644
index 0000000..22e8254
--- /dev/null
+++ b/tests/benchmark/res/raw/netstats-many-uids-zip
Binary files differ
diff --git a/tests/benchmark/src/android/net/netstats/benchmarktests/NetworkStatsCollectionTest.kt b/tests/benchmark/src/android/net/netstats/benchmarktests/NetworkStatsCollectionTest.kt
new file mode 100644
index 0000000..177014f
--- /dev/null
+++ b/tests/benchmark/src/android/net/netstats/benchmarktests/NetworkStatsCollectionTest.kt
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.net.benchmarktests
+
+import android.net.NetworkStatsCollection
+import androidx.test.InstrumentationRegistry
+import com.android.internal.util.FileRotator.Reader
+import com.android.server.connectivity.benchmarktests.R
+import java.io.BufferedInputStream
+import java.io.DataInputStream
+import java.io.File
+import java.io.FileInputStream
+import java.io.FileOutputStream
+import java.nio.file.Files
+import java.util.concurrent.TimeUnit
+import java.util.zip.ZipInputStream
+import kotlin.test.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+
+@RunWith(JUnit4::class)
+class NetworkStatsCollectionTest {
+    private val DEFAULT_BUFFER_SIZE = 8192
+    private val UID_COLLECTION_BUCKET_DURATION_MS = TimeUnit.HOURS.toMillis(2)
+
+    private val uidTestFiles: List<File> by lazy {
+        // These file generated by using real user dataset which has many uid records and agreed to
+        // share the dataset for testing purpose. These dataset can be extracted from rooted
+        // devices by using "adb pull /data/misc/apexdata/com.android.tethering/netstats" command.
+        val zipInputStream = ZipInputStream(getInputStreamForResource(R.raw.netstats_many_uids_zip))
+        getSortedListForPrefix(unzipToTempDir(zipInputStream), "uid")
+    }
+
+    @Test
+    fun testReadCollection_manyUids() {
+        val collection = NetworkStatsCollection(UID_COLLECTION_BUCKET_DURATION_MS)
+        for (file in uidTestFiles) {
+            readFile(file, collection)
+        }
+    }
+
+    private fun getInputStreamForResource(resourceId: Int): DataInputStream {
+        return DataInputStream(
+            InstrumentationRegistry.getContext()
+                .getResources().openRawResource(resourceId)
+        )
+    }
+
+    private fun unzipToTempDir(zis: ZipInputStream): File {
+        val statsDir =
+            Files.createTempDirectory(NetworkStatsCollectionTest::class.simpleName).toFile()
+        while (true) {
+            val entryName = zis.nextEntry?.name ?: break
+            val file = File(statsDir, entryName)
+            FileOutputStream(file).use { zis.copyTo(it, DEFAULT_BUFFER_SIZE) }
+        }
+        return statsDir
+    }
+
+    // List [xt|uid|uid_tag].<start>-<end> files under the given directory.
+    private fun getSortedListForPrefix(statsDir: File, prefix: String): List<File> {
+        assertTrue(statsDir.exists())
+        return (statsDir.list() ?: arrayOf()).mapNotNull {
+            if (it.startsWith("$prefix.")) File(statsDir, it) else null
+        }.sorted()
+    }
+
+    private fun readFile(file: File, reader: Reader) =
+        BufferedInputStream(FileInputStream(file)).use {
+            reader.read(it)
+        }
+}