Merge "[TNU05.1] Address aosp/1237036 leftover comments"
diff --git a/Tethering/src/com/android/networkstack/tethering/EntitlementManager.java b/Tethering/src/com/android/networkstack/tethering/EntitlementManager.java
index 4c7b2d4..049a9f6 100644
--- a/Tethering/src/com/android/networkstack/tethering/EntitlementManager.java
+++ b/Tethering/src/com/android/networkstack/tethering/EntitlementManager.java
@@ -38,8 +38,6 @@
 import android.net.util.SharedLog;
 import android.os.Bundle;
 import android.os.Handler;
-import android.os.Looper;
-import android.os.Message;
 import android.os.Parcel;
 import android.os.PersistableBundle;
 import android.os.ResultReceiver;
@@ -75,11 +73,6 @@
 
     private final ComponentName mSilentProvisioningService;
     private static final int MS_PER_HOUR = 60 * 60 * 1000;
-    private static final int EVENT_START_PROVISIONING = 0;
-    private static final int EVENT_STOP_PROVISIONING = 1;
-    private static final int EVENT_UPSTREAM_CHANGED = 2;
-    private static final int EVENT_MAYBE_RUN_PROVISIONING = 3;
-    private static final int EVENT_GET_ENTITLEMENT_VALUE = 4;
 
     // The ArraySet contains enabled downstream types, ex:
     // {@link TetheringManager.TETHERING_WIFI}
@@ -90,7 +83,7 @@
     private final int mPermissionChangeMessageCode;
     private final SharedLog mLog;
     private final SparseIntArray mEntitlementCacheValue;
-    private final EntitlementHandler mHandler;
+    private final Handler mHandler;
     private final StateMachine mTetherMasterSM;
     // Key: TetheringManager.TETHERING_*(downstream).
     // Value: TetheringManager.TETHER_ERROR_{NO_ERROR or PROVISION_FAILED}(provisioning result).
@@ -112,10 +105,7 @@
         mEntitlementCacheValue = new SparseIntArray();
         mTetherMasterSM = tetherMasterSM;
         mPermissionChangeMessageCode = permissionChangeMessageCode;
-        final Handler masterHandler = tetherMasterSM.getHandler();
-        // Create entitlement's own handler which is associated with TetherMaster thread
-        // let all entitlement processes run in the same thread.
-        mHandler = new EntitlementHandler(masterHandler.getLooper());
+        mHandler = tetherMasterSM.getHandler();
         mContext.registerReceiver(mReceiver, new IntentFilter(ACTION_PROVISIONING_ALARM),
                 null, mHandler);
         mSilentProvisioningService = ComponentName.unflattenFromString(
@@ -172,14 +162,9 @@
      *        provisioning app UI if there is one.
      */
     public void startProvisioningIfNeeded(int downstreamType, boolean showProvisioningUi) {
-        mHandler.sendMessage(mHandler.obtainMessage(EVENT_START_PROVISIONING,
-                downstreamType, encodeBool(showProvisioningUi)));
-    }
+        if (!isValidDownstreamType(downstreamType)) return;
 
-    private void handleStartProvisioningIfNeeded(int type, boolean showProvisioningUi) {
-        if (!isValidDownstreamType(type)) return;
-
-        if (!mCurrentTethers.contains(type)) mCurrentTethers.add(type);
+        if (!mCurrentTethers.contains(downstreamType)) mCurrentTethers.add(downstreamType);
 
         final TetheringConfiguration config = mFetcher.fetchTetheringConfiguration();
         if (isTetherProvisioningRequired(config)) {
@@ -192,9 +177,9 @@
             // till upstream change to cellular.
             if (mUsingCellularAsUpstream) {
                 if (showProvisioningUi) {
-                    runUiTetherProvisioning(type, config.activeDataSubId);
+                    runUiTetherProvisioning(downstreamType, config.activeDataSubId);
                 } else {
-                    runSilentTetherProvisioning(type, config.activeDataSubId);
+                    runSilentTetherProvisioning(downstreamType, config.activeDataSubId);
                 }
                 mNeedReRunProvisioningUi = false;
             } else {
@@ -211,10 +196,6 @@
      * @param type tethering type from TetheringManager.TETHERING_{@code *}
      */
     public void stopProvisioningIfNeeded(int type) {
-        mHandler.sendMessage(mHandler.obtainMessage(EVENT_STOP_PROVISIONING, type, 0));
-    }
-
-    private void handleStopProvisioningIfNeeded(int type) {
         if (!isValidDownstreamType(type)) return;
 
         mCurrentTethers.remove(type);
@@ -230,11 +211,6 @@
      * @param isCellular whether tethering upstream is cellular.
      */
     public void notifyUpstream(boolean isCellular) {
-        mHandler.sendMessage(mHandler.obtainMessage(
-                EVENT_UPSTREAM_CHANGED, encodeBool(isCellular), 0));
-    }
-
-    private void handleNotifyUpstream(boolean isCellular) {
         if (DBG) {
             mLog.i("notifyUpstream: " + isCellular
                     + ", mCellularUpstreamPermitted: " + mCellularUpstreamPermitted
@@ -244,16 +220,17 @@
 
         if (mUsingCellularAsUpstream) {
             final TetheringConfiguration config = mFetcher.fetchTetheringConfiguration();
-            handleMaybeRunProvisioning(config);
+            maybeRunProvisioning(config);
         }
     }
 
     /** Run provisioning if needed */
     public void maybeRunProvisioning() {
-        mHandler.sendMessage(mHandler.obtainMessage(EVENT_MAYBE_RUN_PROVISIONING));
+        final TetheringConfiguration config = mFetcher.fetchTetheringConfiguration();
+        maybeRunProvisioning(config);
     }
 
-    private void handleMaybeRunProvisioning(final TetheringConfiguration config) {
+    private void maybeRunProvisioning(final TetheringConfiguration config) {
         if (mCurrentTethers.size() == 0 || !isTetherProvisioningRequired(config)) {
             return;
         }
@@ -319,7 +296,7 @@
         }
 
         if (mUsingCellularAsUpstream) {
-            handleMaybeRunProvisioning(config);
+            maybeRunProvisioning(config);
         }
     }
 
@@ -494,46 +471,6 @@
         }
     };
 
-    private class EntitlementHandler extends Handler {
-        EntitlementHandler(Looper looper) {
-            super(looper);
-        }
-
-        @Override
-        public void handleMessage(Message msg) {
-            switch (msg.what) {
-                case EVENT_START_PROVISIONING:
-                    handleStartProvisioningIfNeeded(msg.arg1, toBool(msg.arg2));
-                    break;
-                case EVENT_STOP_PROVISIONING:
-                    handleStopProvisioningIfNeeded(msg.arg1);
-                    break;
-                case EVENT_UPSTREAM_CHANGED:
-                    handleNotifyUpstream(toBool(msg.arg1));
-                    break;
-                case EVENT_MAYBE_RUN_PROVISIONING:
-                    final TetheringConfiguration config = mFetcher.fetchTetheringConfiguration();
-                    handleMaybeRunProvisioning(config);
-                    break;
-                case EVENT_GET_ENTITLEMENT_VALUE:
-                    handleRequestLatestTetheringEntitlementValue(msg.arg1,
-                            (ResultReceiver) msg.obj, toBool(msg.arg2));
-                    break;
-                default:
-                    mLog.log("Unknown event: " + msg.what);
-                    break;
-            }
-        }
-    }
-
-    private static boolean toBool(int encodedBoolean) {
-        return encodedBoolean != 0;
-    }
-
-    private static int encodeBool(boolean b) {
-        return b ? 1 : 0;
-    }
-
     private static boolean isValidDownstreamType(int type) {
         switch (type) {
             case TETHERING_BLUETOOTH:
@@ -644,13 +581,6 @@
     /** Get the last value of the tethering entitlement check. */
     public void requestLatestTetheringEntitlementResult(int downstream, ResultReceiver receiver,
             boolean showEntitlementUi) {
-        mHandler.sendMessage(mHandler.obtainMessage(EVENT_GET_ENTITLEMENT_VALUE,
-                downstream, encodeBool(showEntitlementUi), receiver));
-
-    }
-
-    private void handleRequestLatestTetheringEntitlementValue(int downstream,
-            ResultReceiver receiver, boolean showEntitlementUi) {
         if (!isValidDownstreamType(downstream)) {
             receiver.send(TETHER_ERROR_ENTITLEMENT_UNKNOWN, null);
             return;
diff --git a/Tethering/src/com/android/networkstack/tethering/Tethering.java b/Tethering/src/com/android/networkstack/tethering/Tethering.java
index 9a95d44..14d2886 100644
--- a/Tethering/src/com/android/networkstack/tethering/Tethering.java
+++ b/Tethering/src/com/android/networkstack/tethering/Tethering.java
@@ -1953,10 +1953,12 @@
     /** Get the latest value of the tethering entitlement check. */
     void requestLatestTetheringEntitlementResult(int type, ResultReceiver receiver,
             boolean showEntitlementUi) {
-        if (receiver != null) {
+        if (receiver == null) return;
+
+        mHandler.post(() -> {
             mEntitlementMgr.requestLatestTetheringEntitlementResult(type, receiver,
                     showEntitlementUi);
-        }
+        });
     }
 
     /** Register tethering event callback */
diff --git a/Tethering/tests/integration/Android.bp b/Tethering/tests/integration/Android.bp
index 620261b..6b751af 100644
--- a/Tethering/tests/integration/Android.bp
+++ b/Tethering/tests/integration/Android.bp
@@ -13,19 +13,12 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 //
-
-android_test {
-    name: "TetheringIntegrationTests",
-    certificate: "platform",
-    platform_apis: true,
+java_defaults {
+    name: "TetheringIntegrationTestsDefaults",
     srcs: [
         "src/**/*.java",
         "src/**/*.kt",
     ],
-    test_suites: [
-        "device-tests",
-        "mts",
-    ],
     static_libs: [
         "NetworkStackApiStableLib",
         "androidx.test.rules",
@@ -44,4 +37,49 @@
         "libdexmakerjvmtiagent",
         "libstaticjvmtiagent",
     ],
+    jarjar_rules: ":NetworkStackJarJarRules",
 }
+
+android_library {
+    name: "TetheringIntegrationTestsLib",
+    platform_apis: true,
+    defaults: ["TetheringIntegrationTestsDefaults"],
+    visibility: ["//cts/tests/tests/tethering"]
+}
+
+android_test {
+    name: "TetheringIntegrationTests",
+    platform_apis: true,
+    defaults: ["TetheringIntegrationTestsDefaults"],
+    test_suites: [
+        "device-tests",
+        "mts",
+    ],
+    compile_multilib: "both",
+}
+
+// Special version of the tethering tests that includes all tests necessary for code coverage
+// purposes. This is currently the union of TetheringTests, TetheringIntegrationTests and
+// NetworkStackTests.
+android_test {
+    name: "TetheringCoverageTests",
+    certificate: "platform",
+    platform_apis: true,
+    test_suites: ["device-tests", "mts"],
+    test_config: "AndroidTest_Coverage.xml",
+    defaults: ["libnetworkstackutilsjni_deps"],
+    static_libs: [
+        "NetworkStackTestsLib",
+        "TetheringTestsLib",
+        "TetheringIntegrationTestsLib",
+    ],
+    jni_libs: [
+        // For mockito extended
+        "libdexmakerjvmtiagent",
+        "libstaticjvmtiagent",
+        // For NetworkStackUtils included in NetworkStackBase
+        "libnetworkstackutilsjni",
+    ],
+    compile_multilib: "both",
+    manifest: "AndroidManifest_coverage.xml",
+}
\ No newline at end of file
diff --git a/Tethering/tests/integration/AndroidManifest.xml b/Tethering/tests/integration/AndroidManifest.xml
index 233ba40..fddfaad 100644
--- a/Tethering/tests/integration/AndroidManifest.xml
+++ b/Tethering/tests/integration/AndroidManifest.xml
@@ -17,7 +17,6 @@
           package="com.android.networkstack.tethering.tests.integration">
 
     <uses-permission android:name="android.permission.INTERNET"/>
-    <uses-permission android:name="android.permission.TETHER_PRIVILEGED"/>
 
     <application android:debuggable="true">
         <uses-library android:name="android.test.runner" />
diff --git a/Tethering/tests/integration/AndroidManifest_coverage.xml b/Tethering/tests/integration/AndroidManifest_coverage.xml
new file mode 100644
index 0000000..06de00d
--- /dev/null
+++ b/Tethering/tests/integration/AndroidManifest_coverage.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2020 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"
+          xmlns:tools="http://schemas.android.com/tools"
+          package="com.android.networkstack.tethering.tests.coverage">
+
+    <application tools:replace="android:label"
+                 android:debuggable="true"
+                 android:label="Tethering coverage tests">
+        <uses-library android:name="android.test.runner" />
+    </application>
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
+                     android:targetPackage="com.android.networkstack.tethering.tests.coverage"
+                     android:label="Tethering coverage tests">
+    </instrumentation>
+</manifest>
diff --git a/Tethering/tests/integration/AndroidTest_Coverage.xml b/Tethering/tests/integration/AndroidTest_Coverage.xml
new file mode 100644
index 0000000..3def209
--- /dev/null
+++ b/Tethering/tests/integration/AndroidTest_Coverage.xml
@@ -0,0 +1,12 @@
+<configuration description="Runs coverage tests for Tethering">
+    <target_preparer class="com.android.tradefed.targetprep.TestAppInstallSetup">
+        <option name="test-file-name" value="TetheringCoverageTests.apk" />
+    </target_preparer>
+
+    <option name="test-tag" value="TetheringCoverageTests" />
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="package" value="com.android.networkstack.tethering.tests.coverage" />
+        <option name="runner" value="androidx.test.runner.AndroidJUnitRunner" />
+        <option name="hidden-api-checks" value="false"/>
+    </test>
+</configuration>
\ No newline at end of file
diff --git a/Tethering/tests/integration/src/android/net/EthernetTetheringTest.java b/Tethering/tests/integration/src/android/net/EthernetTetheringTest.java
index b02bb23..4bac9da 100644
--- a/Tethering/tests/integration/src/android/net/EthernetTetheringTest.java
+++ b/Tethering/tests/integration/src/android/net/EthernetTetheringTest.java
@@ -18,6 +18,7 @@
 
 import static android.Manifest.permission.MANAGE_TEST_NETWORKS;
 import static android.Manifest.permission.NETWORK_SETTINGS;
+import static android.Manifest.permission.TETHER_PRIVILEGED;
 import static android.net.TetheringManager.TETHERING_ETHERNET;
 
 import static org.junit.Assert.assertEquals;
@@ -109,7 +110,8 @@
         mTetheredInterfaceRequester = new TetheredInterfaceRequester(mHandler, mEm);
         // Needed to create a TestNetworkInterface, to call requestTetheredInterface, and to receive
         // tethered client callbacks.
-        mUiAutomation.adoptShellPermissionIdentity(MANAGE_TEST_NETWORKS, NETWORK_SETTINGS);
+        mUiAutomation.adoptShellPermissionIdentity(
+                MANAGE_TEST_NETWORKS, NETWORK_SETTINGS, TETHER_PRIVILEGED);
     }
 
     private void cleanUp() throws Exception {
diff --git a/Tethering/tests/unit/Android.bp b/Tethering/tests/unit/Android.bp
index ddc095f..499ac0e 100644
--- a/Tethering/tests/unit/Android.bp
+++ b/Tethering/tests/unit/Android.bp
@@ -14,36 +14,30 @@
 // limitations under the License.
 //
 
-android_test {
-    name: "TetheringTests",
-    certificate: "platform",
+java_defaults {
+    name: "TetheringTestsDefaults",
     srcs: [
         "src/**/*.java",
         "src/**/*.kt",
     ],
-    test_suites: [
-        "device-tests",
-        "mts",
-    ],
-    compile_multilib: "both",
     static_libs: [
+        "TetheringApiCurrentLib",
         "androidx.test.rules",
         "frameworks-base-testutils",
-        "net-tests-utils",
         "mockito-target-extended-minus-junit4",
-        "TetheringApiCurrentLib",
+        "net-tests-utils",
         "testables",
     ],
     // TODO(b/147200698) change sdk_version to module-current and
     // remove framework-minus-apex, ext, and framework-res
     sdk_version: "core_platform",
     libs: [
-        "framework-minus-apex",
-        "ext",
-        "framework-res",
         "android.test.runner",
         "android.test.base",
         "android.test.mock",
+        "ext",
+        "framework-minus-apex",
+        "framework-res",
         "framework-tethering",
     ],
     jni_libs: [
@@ -53,3 +47,25 @@
     ],
     jarjar_rules: "jarjar-rules.txt",
 }
+
+// Library containing the unit tests. This is used by the coverage test target to pull in the
+// unit test code. It is not currently used by the tests themselves because all the build
+// configuration needed by the tests is in the TetheringTestsDefaults rule.
+android_library {
+    name: "TetheringTestsLib",
+    defaults: ["TetheringTestsDefaults"],
+    visibility: [
+        "//frameworks/base/packages/Tethering/tests/integration",
+    ]
+}
+
+android_test {
+    name: "TetheringTests",
+    certificate: "platform",
+    test_suites: [
+        "device-tests",
+        "mts",
+    ],
+    defaults: ["TetheringTestsDefaults"],
+    compile_multilib: "both",
+}