Merge "Test onBandwidthUpdateRequested"
diff --git a/tests/cts/hostside/Android.bp b/tests/cts/hostside/Android.bp
index a8cc95b..741c961 100644
--- a/tests/cts/hostside/Android.bp
+++ b/tests/cts/hostside/Android.bp
@@ -24,7 +24,6 @@
     // Tag this module as a cts test artifact
     test_suites: [
         "cts",
-        "vts",
         "vts10",
         "general-tests",
     ],
diff --git a/tests/cts/hostside/app/Android.bp b/tests/cts/hostside/app/Android.bp
index 49aacd9..2362389 100644
--- a/tests/cts/hostside/app/Android.bp
+++ b/tests/cts/hostside/app/Android.bp
@@ -33,7 +33,6 @@
     // Tag this module as a cts test artifact
     test_suites: [
         "cts",
-        "vts",
         "vts10",
         "general-tests",
     ],
diff --git a/tests/cts/hostside/app2/Android.bp b/tests/cts/hostside/app2/Android.bp
index 0bb0d2f..a6e9b11 100644
--- a/tests/cts/hostside/app2/Android.bp
+++ b/tests/cts/hostside/app2/Android.bp
@@ -23,7 +23,6 @@
     // Tag this module as a cts test artifact
     test_suites: [
         "cts",
-        "vts",
         "vts10",
         "general-tests",
     ],
diff --git a/tests/cts/net/Android.bp b/tests/cts/net/Android.bp
index d77f416..76bb27e 100644
--- a/tests/cts/net/Android.bp
+++ b/tests/cts/net/Android.bp
@@ -64,7 +64,6 @@
     defaults: ["CtsNetTestCasesDefaults"],
     test_suites: [
         "cts",
-        "vts",
         "vts10",
         "general-tests",
     ],
diff --git a/tests/cts/net/api23Test/Android.bp b/tests/cts/net/api23Test/Android.bp
index 614a5a2..ffeef48 100644
--- a/tests/cts/net/api23Test/Android.bp
+++ b/tests/cts/net/api23Test/Android.bp
@@ -45,7 +45,6 @@
     // Tag this module as a cts test artifact
     test_suites: [
         "cts",
-        "vts",
         "vts10",
         "general-tests",
     ],
diff --git a/tests/cts/net/appForApi23/Android.bp b/tests/cts/net/appForApi23/Android.bp
index 17cfe38..399c199 100644
--- a/tests/cts/net/appForApi23/Android.bp
+++ b/tests/cts/net/appForApi23/Android.bp
@@ -26,7 +26,6 @@
     // Tag this module as a cts test artifact
     test_suites: [
         "cts",
-        "vts",
         "vts10",
         "general-tests",
     ],
diff --git a/tests/cts/net/ipsec/Android.bp b/tests/cts/net/ipsec/Android.bp
index 86969c3..8c073c9 100644
--- a/tests/cts/net/ipsec/Android.bp
+++ b/tests/cts/net/ipsec/Android.bp
@@ -40,7 +40,6 @@
     test_suites: [
         "cts",
         "mts",
-        "vts",
         "general-tests",
     ],
 }
diff --git a/tests/cts/net/native/qtaguid/Android.bp b/tests/cts/net/native/qtaguid/Android.bp
index 054937b..23a0cf7 100644
--- a/tests/cts/net/native/qtaguid/Android.bp
+++ b/tests/cts/net/native/qtaguid/Android.bp
@@ -42,7 +42,6 @@
     // Tag this module as a cts test artifact
     test_suites: [
         "cts",
-        "vts",
         "vts10",
     ],
 
diff --git a/tests/cts/net/src/android/net/cts/DhcpInfoTest.java b/tests/cts/net/src/android/net/cts/DhcpInfoTest.java
index 085fdd9..b8d2392 100644
--- a/tests/cts/net/src/android/net/cts/DhcpInfoTest.java
+++ b/tests/cts/net/src/android/net/cts/DhcpInfoTest.java
@@ -16,48 +16,99 @@
 
 package android.net.cts;
 
+import static android.net.shared.Inet4AddressUtils.inet4AddressToIntHTL;
+
+import static com.android.testutils.MiscAssertsKt.assertFieldCountEquals;
+import static com.android.testutils.ParcelUtilsKt.parcelingRoundTrip;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import android.annotation.Nullable;
 import android.net.DhcpInfo;
-import android.test.AndroidTestCase;
 
-public class DhcpInfoTest extends AndroidTestCase {
+import androidx.test.runner.AndroidJUnit4;
 
-    public void testConstructor() {
-        new DhcpInfo();
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.net.Inet4Address;
+import java.net.InetAddress;
+
+@RunWith(AndroidJUnit4.class)
+public class DhcpInfoTest {
+    private static final String STR_ADDR1 = "255.255.255.255";
+    private static final String STR_ADDR2 = "127.0.0.1";
+    private static final String STR_ADDR3 = "192.168.1.1";
+    private static final String STR_ADDR4 = "192.168.1.0";
+    private static final int LEASE_TIME = 9999;
+
+    private int ipToInteger(String ipString) throws Exception {
+        return inet4AddressToIntHTL((Inet4Address) InetAddress.getByName(ipString));
     }
 
-    public void testToString() {
-        String expectedDefault = "ipaddr 0.0.0.0 gateway 0.0.0.0 netmask 0.0.0.0 dns1 0.0.0.0 "
-                + "dns2 0.0.0.0 DHCP server 0.0.0.0 lease 0 seconds";
-        String STR_ADDR1 = "255.255.255.255";
-        String STR_ADDR2 = "127.0.0.1";
-        String STR_ADDR3 = "192.168.1.1";
-        String STR_ADDR4 = "192.168.1.0";
-        int leaseTime = 9999;
-        String expected = "ipaddr " + STR_ADDR1 + " gateway " + STR_ADDR2 + " netmask "
-                + STR_ADDR3 + " dns1 " + STR_ADDR4 + " dns2 " + STR_ADDR4 + " DHCP server "
-                + STR_ADDR2 + " lease " + leaseTime + " seconds";
-
-        DhcpInfo dhcpInfo = new DhcpInfo();
-
-        // Test default string.
-        assertEquals(expectedDefault, dhcpInfo.toString());
-
+    private DhcpInfo createDhcpInfoObject() throws Exception {
+        final DhcpInfo dhcpInfo = new DhcpInfo();
         dhcpInfo.ipAddress = ipToInteger(STR_ADDR1);
         dhcpInfo.gateway = ipToInteger(STR_ADDR2);
         dhcpInfo.netmask = ipToInteger(STR_ADDR3);
         dhcpInfo.dns1 = ipToInteger(STR_ADDR4);
         dhcpInfo.dns2 = ipToInteger(STR_ADDR4);
         dhcpInfo.serverAddress = ipToInteger(STR_ADDR2);
-        dhcpInfo.leaseDuration = leaseTime;
+        dhcpInfo.leaseDuration = LEASE_TIME;
+        return dhcpInfo;
+    }
 
+    @Test
+    public void testConstructor() {
+        new DhcpInfo();
+    }
+
+    @Test
+    public void testToString() throws Exception {
+        final String expectedDefault = "ipaddr 0.0.0.0 gateway 0.0.0.0 netmask 0.0.0.0 "
+                + "dns1 0.0.0.0 dns2 0.0.0.0 DHCP server 0.0.0.0 lease 0 seconds";
+
+        DhcpInfo dhcpInfo = new DhcpInfo();
+
+        // Test default string.
+        assertEquals(expectedDefault, dhcpInfo.toString());
+
+        dhcpInfo = createDhcpInfoObject();
+
+        final String expected = "ipaddr " + STR_ADDR1 + " gateway " + STR_ADDR2 + " netmask "
+                + STR_ADDR3 + " dns1 " + STR_ADDR4 + " dns2 " + STR_ADDR4 + " DHCP server "
+                + STR_ADDR2 + " lease " + LEASE_TIME + " seconds";
         // Test with new values
         assertEquals(expected, dhcpInfo.toString());
     }
 
-    private int ipToInteger(String ipString) {
-        String ipSegs[] = ipString.split("[.]");
-        int tmp = Integer.parseInt(ipSegs[3]) << 24 | Integer.parseInt(ipSegs[2]) << 16 |
-            Integer.parseInt(ipSegs[1]) << 8 | Integer.parseInt(ipSegs[0]);
-        return tmp;
+    private boolean dhcpInfoEquals(@Nullable DhcpInfo left, @Nullable DhcpInfo right) {
+        if (left == null && right == null) return true;
+
+        if (left == null || right == null) return false;
+
+        return left.ipAddress == right.ipAddress
+                && left.gateway == right.gateway
+                && left.netmask == right.netmask
+                && left.dns1 == right.dns1
+                && left.dns2 == right.dns2
+                && left.serverAddress == right.serverAddress
+                && left.leaseDuration == right.leaseDuration;
+    }
+
+    @Test
+    public void testParcelDhcpInfo() throws Exception {
+        // Cannot use assertParcelSane() here because this requires .equals() to work as
+        // defined, but DhcpInfo has a different legacy behavior that we cannot change.
+        final DhcpInfo dhcpInfo = createDhcpInfoObject();
+        assertFieldCountEquals(7, DhcpInfo.class);
+
+        final DhcpInfo dhcpInfoRoundTrip = parcelingRoundTrip(dhcpInfo);
+        assertTrue(dhcpInfoEquals(null, null));
+        assertFalse(dhcpInfoEquals(null, dhcpInfoRoundTrip));
+        assertFalse(dhcpInfoEquals(dhcpInfo, null));
+        assertTrue(dhcpInfoEquals(dhcpInfo, dhcpInfoRoundTrip));
     }
 }
diff --git a/tests/cts/net/src/android/net/cts/ProxyInfoTest.java b/tests/cts/net/src/android/net/cts/ProxyInfoTest.java
new file mode 100644
index 0000000..1c5624c
--- /dev/null
+++ b/tests/cts/net/src/android/net/cts/ProxyInfoTest.java
@@ -0,0 +1,135 @@
+/*
+ * 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.net.cts;
+
+import static org.junit.Assert.assertArrayEquals;
+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 android.net.ProxyInfo;
+import android.net.Uri;
+import android.os.Build;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.testutils.DevSdkIgnoreRule;
+import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+@RunWith(AndroidJUnit4.class)
+public final class ProxyInfoTest {
+    private static final String TEST_HOST = "test.example.com";
+    private static final int TEST_PORT = 5566;
+    private static final Uri TEST_URI = Uri.parse("https://test.example.com");
+    // This matches android.net.ProxyInfo#LOCAL_EXCL_LIST
+    private static final String LOCAL_EXCL_LIST = "";
+    // This matches android.net.ProxyInfo#LOCAL_HOST
+    private static final String LOCAL_HOST = "localhost";
+    // This matches android.net.ProxyInfo#LOCAL_PORT
+    private static final int LOCAL_PORT = -1;
+
+    @Rule
+    public final DevSdkIgnoreRule ignoreRule = new DevSdkIgnoreRule();
+
+    @Test
+    public void testConstructor() {
+        final ProxyInfo proxy = new ProxyInfo((ProxyInfo) null);
+        checkEmpty(proxy);
+
+        assertEquals(proxy, new ProxyInfo(proxy));
+    }
+
+    @Test
+    public void testBuildDirectProxy() {
+        final ProxyInfo proxy1 = ProxyInfo.buildDirectProxy(TEST_HOST, TEST_PORT);
+
+        assertEquals(TEST_HOST, proxy1.getHost());
+        assertEquals(TEST_PORT, proxy1.getPort());
+        assertArrayEquals(new String[0], proxy1.getExclusionList());
+        assertEquals(Uri.EMPTY, proxy1.getPacFileUrl());
+
+        final List<String> exclList = new ArrayList<>();
+        exclList.add("localhost");
+        exclList.add("*.exclusion.com");
+        final ProxyInfo proxy2 = ProxyInfo.buildDirectProxy(TEST_HOST, TEST_PORT, exclList);
+
+        assertEquals(TEST_HOST, proxy2.getHost());
+        assertEquals(TEST_PORT, proxy2.getPort());
+        assertArrayEquals(exclList.toArray(new String[0]), proxy2.getExclusionList());
+        assertEquals(Uri.EMPTY, proxy2.getPacFileUrl());
+    }
+
+    @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+    public void testBuildPacProxy() {
+        final ProxyInfo proxy1 = ProxyInfo.buildPacProxy(TEST_URI);
+
+        assertEquals(LOCAL_HOST, proxy1.getHost());
+        assertEquals(LOCAL_PORT, proxy1.getPort());
+        assertArrayEquals(LOCAL_EXCL_LIST.toLowerCase(Locale.ROOT).split(","),
+                proxy1.getExclusionList());
+        assertEquals(TEST_URI, proxy1.getPacFileUrl());
+
+        final ProxyInfo proxy2 = ProxyInfo.buildPacProxy(TEST_URI, TEST_PORT);
+
+        assertEquals(LOCAL_HOST, proxy2.getHost());
+        assertEquals(TEST_PORT, proxy2.getPort());
+        assertArrayEquals(LOCAL_EXCL_LIST.toLowerCase(Locale.ROOT).split(","),
+                proxy2.getExclusionList());
+        assertEquals(TEST_URI, proxy2.getPacFileUrl());
+    }
+
+    @Test
+    public void testIsValid() {
+        final ProxyInfo proxy1 = ProxyInfo.buildDirectProxy(TEST_HOST, TEST_PORT);
+        assertTrue(proxy1.isValid());
+
+        // Given empty host
+        final ProxyInfo proxy2 = ProxyInfo.buildDirectProxy("", TEST_PORT);
+        assertFalse(proxy2.isValid());
+        // Given invalid host
+        final ProxyInfo proxy3 = ProxyInfo.buildDirectProxy(".invalid.com", TEST_PORT);
+        assertFalse(proxy3.isValid());
+        // Given invalid port.
+        final ProxyInfo proxy4 = ProxyInfo.buildDirectProxy(TEST_HOST, 0);
+        assertFalse(proxy4.isValid());
+        // Given another invalid port
+        final ProxyInfo proxy5 = ProxyInfo.buildDirectProxy(TEST_HOST, 65536);
+        assertFalse(proxy5.isValid());
+        // Given invalid exclusion list
+        final List<String> exclList = new ArrayList<>();
+        exclList.add(".invalid.com");
+        exclList.add("%.test.net");
+        final ProxyInfo proxy6 = ProxyInfo.buildDirectProxy(TEST_HOST, TEST_PORT, exclList);
+        assertFalse(proxy6.isValid());
+    }
+
+    private void checkEmpty(ProxyInfo proxy) {
+        assertNull(proxy.getHost());
+        assertEquals(0, proxy.getPort());
+        assertNull(proxy.getExclusionList());
+        assertEquals(Uri.EMPTY, proxy.getPacFileUrl());
+    }
+}
diff --git a/tests/cts/net/src/android/net/cts/TrafficStatsTest.java b/tests/cts/net/src/android/net/cts/TrafficStatsTest.java
index 12ab370..577e24a 100755
--- a/tests/cts/net/src/android/net/cts/TrafficStatsTest.java
+++ b/tests/cts/net/src/android/net/cts/TrafficStatsTest.java
@@ -61,6 +61,11 @@
         assertTrue(TrafficStats.getTotalRxBytes() >= 0);
     }
 
+    public void testValidPacketStats() {
+        assertTrue(TrafficStats.getTxPackets("lo") >= 0);
+        assertTrue(TrafficStats.getRxPackets("lo") >= 0);
+    }
+
     public void testThreadStatsTag() throws Exception {
         TrafficStats.setThreadStatsTag(0xf00d);
         assertTrue("Tag didn't stick", TrafficStats.getThreadStatsTag() == 0xf00d);
@@ -104,6 +109,8 @@
         final long uidRxBytesBefore = TrafficStats.getUidRxBytes(Process.myUid());
         final long uidTxPacketsBefore = TrafficStats.getUidTxPackets(Process.myUid());
         final long uidRxPacketsBefore = TrafficStats.getUidRxPackets(Process.myUid());
+        final long ifaceTxPacketsBefore = TrafficStats.getTxPackets("lo");
+        final long ifaceRxPacketsBefore = TrafficStats.getRxPackets("lo");
 
         // Transfer 1MB of data across an explicitly localhost socket.
         final int byteCount = 1024;
@@ -182,6 +189,10 @@
         final long uidTxDeltaPackets = uidTxPacketsAfter - uidTxPacketsBefore;
         final long uidRxDeltaBytes = uidRxBytesAfter - uidRxBytesBefore;
         final long uidRxDeltaPackets = uidRxPacketsAfter - uidRxPacketsBefore;
+        final long ifaceTxPacketsAfter = TrafficStats.getTxPackets("lo");
+        final long ifaceRxPacketsAfter = TrafficStats.getRxPackets("lo");
+        final long ifaceTxDeltaPackets = ifaceTxPacketsAfter - ifaceTxPacketsBefore;
+        final long ifaceRxDeltaPackets = ifaceRxPacketsAfter - ifaceRxPacketsBefore;
 
         // Localhost traffic *does* count against per-UID stats.
         /*
@@ -209,34 +220,37 @@
                     + deltaRxOtherPackets);
         }
 
-        // Check the per uid stats read from data profiling have the stats expected. The data
-        // profiling snapshot is generated from readNetworkStatsDetail() method in
-        // networkStatsService and in this way we can verify the detail networkStats of a given uid
-        // is correct.
-        NetworkStats.Entry entry = testStats.getTotal(null, Process.myUid());
+        // Check that the per-uid stats obtained from data profiling contain the expected values.
+        // The data profiling snapshot is generated from the readNetworkStatsDetail() method in
+        // networkStatsService, so it's possible to verify that the detailed stats for a given
+        // uid are correct.
+        final NetworkStats.Entry entry = testStats.getTotal(null, Process.myUid());
+        final long pktBytes = tcpPacketToIpBytes(packetCount, byteCount);
+        final long pktWithNoDataBytes = tcpPacketToIpBytes(packetCount, 0);
+        final long minExpExtraPktBytes = tcpPacketToIpBytes(minExpectedExtraPackets, 0);
+        final long maxExpExtraPktBytes = tcpPacketToIpBytes(maxExpectedExtraPackets, 0);
+        final long deltaTxOtherPktBytes = tcpPacketToIpBytes(deltaTxOtherPackets, 0);
+        final long deltaRxOtherPktBytes  = tcpPacketToIpBytes(deltaRxOtherPackets, 0);
         assertInRange("txPackets detail", entry.txPackets, packetCount + minExpectedExtraPackets,
                 uidTxDeltaPackets);
         assertInRange("rxPackets detail", entry.rxPackets, packetCount + minExpectedExtraPackets,
                 uidRxDeltaPackets);
-        assertInRange("txBytes detail", entry.txBytes, tcpPacketToIpBytes(packetCount, byteCount)
-                + tcpPacketToIpBytes(minExpectedExtraPackets, 0), uidTxDeltaBytes);
-        assertInRange("rxBytes detail", entry.rxBytes, tcpPacketToIpBytes(packetCount, byteCount)
-                + tcpPacketToIpBytes(minExpectedExtraPackets, 0), uidRxDeltaBytes);
-
+        assertInRange("txBytes detail", entry.txBytes, pktBytes + minExpExtraPktBytes,
+                uidTxDeltaBytes);
+        assertInRange("rxBytes detail", entry.rxBytes, pktBytes + minExpExtraPktBytes,
+                uidRxDeltaBytes);
         assertInRange("uidtxp", uidTxDeltaPackets, packetCount + minExpectedExtraPackets,
                 packetCount + packetCount + maxExpectedExtraPackets + deltaTxOtherPackets);
         assertInRange("uidrxp", uidRxDeltaPackets, packetCount + minExpectedExtraPackets,
                 packetCount + packetCount + maxExpectedExtraPackets + deltaRxOtherPackets);
-        assertInRange("uidtxb", uidTxDeltaBytes, tcpPacketToIpBytes(packetCount, byteCount)
-                + tcpPacketToIpBytes(minExpectedExtraPackets, 0),
-                tcpPacketToIpBytes(packetCount, byteCount)
-                + tcpPacketToIpBytes(packetCount + maxExpectedExtraPackets
-                + deltaTxOtherPackets, 0));
-        assertInRange("uidrxb", uidRxDeltaBytes, tcpPacketToIpBytes(packetCount, byteCount)
-                + tcpPacketToIpBytes(minExpectedExtraPackets, 0),
-                tcpPacketToIpBytes(packetCount, byteCount)
-                + tcpPacketToIpBytes(packetCount + maxExpectedExtraPackets
-                + deltaRxOtherPackets, 0));
+        assertInRange("uidtxb", uidTxDeltaBytes, pktBytes + minExpExtraPktBytes,
+                pktBytes + pktWithNoDataBytes + maxExpExtraPktBytes + deltaTxOtherPktBytes);
+        assertInRange("uidrxb", uidRxDeltaBytes, pktBytes + minExpExtraPktBytes,
+                pktBytes + pktWithNoDataBytes + maxExpExtraPktBytes + deltaRxOtherPktBytes);
+        assertInRange("iftxp", ifaceTxDeltaPackets, packetCount + minExpectedExtraPackets,
+                packetCount + packetCount + maxExpectedExtraPackets + deltaTxOtherPackets);
+        assertInRange("ifrxp", ifaceRxDeltaPackets, packetCount + minExpectedExtraPackets,
+                packetCount + packetCount + maxExpectedExtraPackets + deltaRxOtherPackets);
 
         // Localhost traffic *does* count against total stats.
         // Check the total stats increased after test data transfer over localhost has been made.
@@ -248,6 +262,10 @@
                 totalTxBytesAfter >= totalTxBytesBefore + uidTxDeltaBytes);
         assertTrue("trxb: " + totalRxBytesBefore + " -> " + totalRxBytesAfter,
                 totalRxBytesAfter >= totalRxBytesBefore + uidRxDeltaBytes);
+        assertTrue("iftxp: " + ifaceTxPacketsBefore + " -> " + ifaceTxPacketsAfter,
+                totalTxPacketsAfter >= totalTxPacketsBefore + ifaceTxDeltaPackets);
+        assertTrue("ifrxp: " + ifaceRxPacketsBefore + " -> " + ifaceRxPacketsAfter,
+                totalRxPacketsAfter >= totalRxPacketsBefore + ifaceRxDeltaPackets);
 
         // If the adb TCP port is opened, this test may be run by adb over network.
         // Huge amount of data traffic might go through the network and accounted into total packets
diff --git a/tests/cts/tethering/src/android/tethering/cts/TetheringManagerTest.java b/tests/cts/tethering/src/android/tethering/cts/TetheringManagerTest.java
index 86fe54c..b132982 100644
--- a/tests/cts/tethering/src/android/tethering/cts/TetheringManagerTest.java
+++ b/tests/cts/tethering/src/android/tethering/cts/TetheringManagerTest.java
@@ -29,9 +29,14 @@
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.net.LinkAddress;
+import android.net.Network;
+import android.net.TetheredClient;
 import android.net.TetheringManager;
+import android.net.TetheringManager.TetheringEventCallback;
+import android.net.TetheringManager.TetheringInterfaceRegexps;
 import android.net.TetheringManager.TetheringRequest;
 
+import androidx.annotation.NonNull;
 import androidx.test.InstrumentationRegistry;
 import androidx.test.runner.AndroidJUnit4;
 
@@ -42,6 +47,8 @@
 
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.TimeUnit;
 
@@ -195,8 +202,12 @@
         }
     }
 
-    private static boolean isIfaceMatch(final String[] ifaceRegexs,
-            final ArrayList<String> ifaces) {
+    private static boolean isIfaceMatch(final List<String> ifaceRegexs,
+            final List<String> ifaces) {
+        return isIfaceMatch(ifaceRegexs.toArray(new String[0]), ifaces);
+    }
+
+    private static boolean isIfaceMatch(final String[] ifaceRegexs, final List<String> ifaces) {
         if (ifaceRegexs == null) fail("ifaceRegexs should not be null");
 
         if (ifaces == null) return false;
@@ -251,4 +262,170 @@
         assertTrue(tr2.isExemptFromEntitlementCheck());
         assertFalse(tr2.getShouldShowEntitlementUi());
     }
+
+    // Must poll the callback before looking at the member.
+    private static class TestTetheringEventCallback implements TetheringEventCallback {
+        public enum CallbackType {
+            ON_SUPPORTED,
+            ON_UPSTREAM,
+            ON_TETHERABLE_REGEX,
+            ON_TETHERABLE_IFACES,
+            ON_TETHERED_IFACES,
+            ON_ERROR,
+            ON_CLIENTS,
+        };
+
+        public static class CallbackValue {
+            public final CallbackType callbackType;
+            public final Object callbackParam;
+            public final int callbackParam2;
+
+            private CallbackValue(final CallbackType type, final Object param, final int param2) {
+                this.callbackType = type;
+                this.callbackParam = param;
+                this.callbackParam2 = param2;
+            }
+        }
+        private final LinkedBlockingQueue<CallbackValue> mCallbacks = new LinkedBlockingQueue<>();
+
+        private TetheringInterfaceRegexps mTetherableRegex;
+        private List<String> mTetherableIfaces;
+        private List<String> mTetheredIfaces;
+
+        @Override
+        public void onTetheringSupported(boolean supported) {
+            mCallbacks.add(new CallbackValue(CallbackType.ON_SUPPORTED, null, 0));
+        }
+
+        @Override
+        public void onUpstreamChanged(Network network) {
+            mCallbacks.add(new CallbackValue(CallbackType.ON_UPSTREAM, network, 0));
+        }
+
+        @Override
+        public void onTetherableInterfaceRegexpsChanged(TetheringInterfaceRegexps reg) {
+            mTetherableRegex = reg;
+            mCallbacks.add(new CallbackValue(CallbackType.ON_TETHERABLE_REGEX, reg, 0));
+        }
+
+        @Override
+        public void onTetherableInterfacesChanged(List<String> interfaces) {
+            mTetherableIfaces = interfaces;
+            mCallbacks.add(new CallbackValue(CallbackType.ON_TETHERABLE_IFACES, interfaces, 0));
+        }
+
+        @Override
+        public void onTetheredInterfacesChanged(List<String> interfaces) {
+            mTetheredIfaces = interfaces;
+            mCallbacks.add(new CallbackValue(CallbackType.ON_TETHERED_IFACES, interfaces, 0));
+        }
+
+        @Override
+        public void onError(String ifName, int error) {
+            mCallbacks.add(new CallbackValue(CallbackType.ON_ERROR, ifName, error));
+        }
+
+        @Override
+        public void onClientsChanged(Collection<TetheredClient> clients) {
+            mCallbacks.add(new CallbackValue(CallbackType.ON_CLIENTS, clients, 0));
+        }
+
+        public CallbackValue pollCallback() {
+            try {
+                return mCallbacks.poll(DEFAULT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+            } catch (InterruptedException e) {
+                fail("Callback not seen");
+            }
+            return null;
+        }
+
+        public void expectTetherableInterfacesChanged(@NonNull List<String> regexs) {
+            while (true) {
+                final CallbackValue cv = pollCallback();
+                if (cv == null) fail("No expected tetherable ifaces callback");
+                if (cv.callbackType != CallbackType.ON_TETHERABLE_IFACES) continue;
+
+                final List<String> interfaces = (List<String>) cv.callbackParam;
+                if (isIfaceMatch(regexs, interfaces)) break;
+            }
+        }
+
+        public void expectTetheredInterfacesChanged(@NonNull List<String> regexs) {
+            while (true) {
+                final CallbackValue cv = pollCallback();
+                if (cv == null) fail("No expected tethered ifaces callback");
+                if (cv.callbackType != CallbackType.ON_TETHERED_IFACES) continue;
+
+                final List<String> interfaces = (List<String>) cv.callbackParam;
+
+                // Null regexs means no active tethering.
+                if (regexs == null) {
+                    if (interfaces.size() == 0) break;
+                } else if (isIfaceMatch(regexs, interfaces)) {
+                    break;
+                }
+            }
+        }
+
+        public void expectCallbackStarted() {
+            // The each bit represent a type from CallbackType.ON_*.
+            // Expect all of callbacks except for ON_ERROR.
+            final int expectedBitMap = 0x7f ^ (1 << CallbackType.ON_ERROR.ordinal());
+            int receivedBitMap = 0;
+            while (receivedBitMap != expectedBitMap) {
+                final CallbackValue cv = pollCallback();
+                if (cv == null) {
+                    fail("No expected callbacks, " + "expected bitmap: "
+                            + expectedBitMap + ", actual: " + receivedBitMap);
+                }
+                receivedBitMap = receivedBitMap | (1 << cv.callbackType.ordinal());
+            }
+        }
+
+        public TetheringInterfaceRegexps getTetheringInterfaceRegexps() {
+            return mTetherableRegex;
+        }
+
+        public List<String> getTetherableInterfaces() {
+            return mTetherableIfaces;
+        }
+
+        public List<String> getTetheredInterfaces() {
+            return mTetheredIfaces;
+        }
+    }
+
+    @Test
+    public void testRegisterTetheringEventCallback() throws Exception {
+        if (!mTM.isTetheringSupported()) return;
+
+        final TestTetheringEventCallback tetherEventCallback = new TestTetheringEventCallback();
+
+        mTM.registerTetheringEventCallback(c -> c.run(), tetherEventCallback);
+        tetherEventCallback.expectCallbackStarted();
+
+        final TetheringInterfaceRegexps tetherableRegexs =
+                tetherEventCallback.getTetheringInterfaceRegexps();
+        final List<String> wifiRegexs = tetherableRegexs.getTetherableWifiRegexs();
+        if (wifiRegexs.size() == 0) return;
+
+        final boolean isIfaceAvailWhenNoTethering =
+                isIfaceMatch(wifiRegexs, tetherEventCallback.getTetherableInterfaces());
+
+        mTM.startTethering(new TetheringRequest.Builder(TETHERING_WIFI).build(), c -> c.run(),
+                new StartTetheringCallback());
+
+        // If interface is already available before starting tethering, the available callback may
+        // not be sent after tethering enabled.
+        if (!isIfaceAvailWhenNoTethering) {
+            tetherEventCallback.expectTetherableInterfacesChanged(wifiRegexs);
+        }
+
+        tetherEventCallback.expectTetheredInterfacesChanged(wifiRegexs);
+
+        mTM.stopTethering(TETHERING_WIFI);
+
+        tetherEventCallback.expectTetheredInterfacesChanged(null);
+        mTM.unregisterTetheringEventCallback(tetherEventCallback);
+    }
 }