Add tests for java.net APIs

Bug: 119393918
Bug: 182166637
Test: atest CtsLibcoreTestCases:libcore.java.net
Change-Id: I81b9325c6c2a1fda6a2446dac5714fa744861a6a
(cherry picked from commit 9fe445af3f65a23f5ebdef53168e480dede07800)
Merged-In: I81b9325c6c2a1fda6a2446dac5714fa744861a6a
diff --git a/luni/src/test/java/libcore/java/net/AuthenticatorTest.java b/luni/src/test/java/libcore/java/net/AuthenticatorTest.java
index 6531107..f14e127 100644
--- a/luni/src/test/java/libcore/java/net/AuthenticatorTest.java
+++ b/luni/src/test/java/libcore/java/net/AuthenticatorTest.java
@@ -73,11 +73,16 @@
         public String getScheme() {
             return getRequestingScheme();
         }
+
+        public String getHost() {
+            return getRequestingHost();
+        }
     }
 
     @Test
     public void testRequestPasswordAuthentication() throws Exception {
         final InetAddress addr = InetAddress.getByName("localhost");
+        final String host = "www.example.com";
         final int port = 42;
         final String protocol = "HTTP";
         final String prompt = "Please enter your password";
@@ -102,10 +107,26 @@
         assertEquals(protocol, auth.getProtocol());
         assertEquals(prompt, auth.getPrompt());
         assertEquals(scheme, auth.getScheme());
+
+        passAuth = Authenticator.requestPasswordAuthentication(
+                host, addr, port, protocol, prompt, scheme);
+
+        assertNotNull(passAuth);
+        assertEquals(userName, passAuth.getUserName());
+        assertEquals(password, String.valueOf(passAuth.getPassword()));
+
+        assertEquals(host, auth.getHost());
+        assertEquals(2, auth.getRequests());
+        assertEquals(addr, auth.getAddr());
+        assertEquals(port, auth.getPort());
+        assertEquals(protocol, auth.getProtocol());
+        assertEquals(prompt, auth.getPrompt());
+        assertEquals(scheme, auth.getScheme());
     }
 
     @Test
     public void testRequestPasswordAuthenticationWithNullAuthenticator() throws Exception {
+        final String host = "www.example.com";
         final InetAddress addr = InetAddress.getByName("localhost");
         final int port = 42;
         final String protocol = "HTTP";
@@ -115,5 +136,8 @@
         Authenticator.setDefault(null);
         assertNull(Authenticator.requestPasswordAuthentication(
                 addr, port, protocol, prompt, scheme));
+
+        assertNull(Authenticator.requestPasswordAuthentication(
+                host, addr, port, protocol, prompt, scheme));
     }
 }
diff --git a/luni/src/test/java/libcore/java/net/InetAddressTest.java b/luni/src/test/java/libcore/java/net/InetAddressTest.java
index 7d59ec0..097e94a 100644
--- a/luni/src/test/java/libcore/java/net/InetAddressTest.java
+++ b/luni/src/test/java/libcore/java/net/InetAddressTest.java
@@ -329,6 +329,18 @@
         } catch (UnknownHostException expected) {
         }
 
+
+        try {
+            InetAddress.getByNameOnNet(invalid, 0 /* NETID_UNSET */);
+            String msg = "Invalid IP address incorrectly recognized as valid: \"" + invalid + "\"";
+            if (InetAddressUtils.parseNumericAddressNoThrowStripOptionalBrackets(invalid) == null) {
+                msg += " (it was probably unexpectedly resolved by this network's DNS)";
+            }
+            msg += ".";
+            fail(msg);
+        } catch (UnknownHostException expected) {
+        }
+
         // exercise negative cache
         try {
             InetAddress.getByName(invalid);
@@ -346,6 +358,7 @@
     @Test
     public void test_getByName_valid(String valid) throws Exception {
         InetAddress.getByName(valid);
+        InetAddress.getAllByNameOnNet(valid, 0 /* NETID_UNSET */);
 
         // exercise positive cache
         InetAddress.getByName(valid);
diff --git a/luni/src/test/java/libcore/java/net/MalformedURLExceptionTest.java b/luni/src/test/java/libcore/java/net/MalformedURLExceptionTest.java
new file mode 100644
index 0000000..b9998da
--- /dev/null
+++ b/luni/src/test/java/libcore/java/net/MalformedURLExceptionTest.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2022 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 libcore.java.net;
+
+
+import static org.junit.Assert.assertNull;
+
+import java.net.MalformedURLException;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class MalformedURLExceptionTest {
+
+    @Test
+    public void testEmptyConstructor() {
+        MalformedURLException e = new MalformedURLException();
+        assertNull(e.getMessage());
+    }
+}
diff --git a/luni/src/test/java/libcore/java/net/NetPermissionTest.java b/luni/src/test/java/libcore/java/net/NetPermissionTest.java
new file mode 100644
index 0000000..db774da
--- /dev/null
+++ b/luni/src/test/java/libcore/java/net/NetPermissionTest.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2022 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 libcore.java.net;
+
+import static org.junit.Assert.assertEquals;
+
+import java.net.NetPermission;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class NetPermissionTest {
+
+    @Test
+    public void testConstructor() {
+        NetPermission permission = new NetPermission("name");
+        assertEquals("", permission.getName());
+
+        permission = new NetPermission("name", "action");
+        assertEquals("", permission.getName());
+        assertEquals("", permission.getActions());
+
+    }
+}
diff --git a/luni/src/test/java/libcore/java/net/NetworkInterfaceTest.java b/luni/src/test/java/libcore/java/net/NetworkInterfaceTest.java
index 0f54b2a..e57b646 100644
--- a/luni/src/test/java/libcore/java/net/NetworkInterfaceTest.java
+++ b/luni/src/test/java/libcore/java/net/NetworkInterfaceTest.java
@@ -115,6 +115,16 @@
         }
     }
 
+    public void testGetByIndex() throws Exception {
+        for (NetworkInterface nif : Collections.list(getNetworkInterfaces())) {
+            int nifIndex = nif.getIndex();
+            if (nifIndex == -1) { // -1 means unknown interface
+                continue;
+            }
+            assertEquals(nif, NetworkInterface.getByIndex(nifIndex));
+        }
+    }
+
     public void testLoopback() throws Exception {
         NetworkInterface lo = NetworkInterface.getByName("lo");
         assertNull(lo.getHardwareAddress());
diff --git a/luni/src/test/java/libcore/java/net/PortUnreachableExceptionTest.java b/luni/src/test/java/libcore/java/net/PortUnreachableExceptionTest.java
index 0eab87d..a85faa1 100644
--- a/luni/src/test/java/libcore/java/net/PortUnreachableExceptionTest.java
+++ b/luni/src/test/java/libcore/java/net/PortUnreachableExceptionTest.java
@@ -17,6 +17,7 @@
 package libcore.java.net;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
 
 import java.net.PortUnreachableException;
 import org.junit.Test;
@@ -27,6 +28,12 @@
 public class PortUnreachableExceptionTest {
 
     @Test
+    public void testEmptyConstructor() {
+        PortUnreachableException e = new PortUnreachableException();
+        assertNull(e.getMessage());
+    }
+
+    @Test
     public void testConstructor_withMsg() {
         String msg = "test message";
         PortUnreachableException e = new PortUnreachableException(msg);
diff --git a/luni/src/test/java/libcore/java/net/SocketPermissionTest.java b/luni/src/test/java/libcore/java/net/SocketPermissionTest.java
new file mode 100644
index 0000000..2bedbef
--- /dev/null
+++ b/luni/src/test/java/libcore/java/net/SocketPermissionTest.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2022 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 libcore.java.net;
+
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.net.SocketPermission;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class SocketPermissionTest {
+
+    @Test
+    public void testGetAction() {
+        String host = "www.example.com";
+        String action = "Connect";
+        SocketPermission permission = new SocketPermission(host, action);
+        // permission.getActions() always returns null on Android.
+        assertNull(permission.getActions());
+    }
+
+    @Test
+    public void testImplies() {
+        String host = "www.example.com";
+        String action = "Connect";
+        SocketPermission permission = new SocketPermission(host, action);
+        // permission.implies() always returns true on Android.
+        assertTrue(permission.implies(null));
+        assertTrue(permission.implies(permission));
+    }
+}
diff --git a/luni/src/test/java/libcore/java/net/URLClassLoaderTest.java b/luni/src/test/java/libcore/java/net/URLClassLoaderTest.java
new file mode 100644
index 0000000..598cf6d
--- /dev/null
+++ b/luni/src/test/java/libcore/java/net/URLClassLoaderTest.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2022 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 libcore.java.net;
+
+import java.io.IOException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class URLClassLoaderTest {
+
+    @Test
+    public void testClose() throws IOException {
+        URL[] urls = new URL[] { new URL("http://www.example.com.") };
+        URLClassLoader classLoader = new URLClassLoader(urls);
+        classLoader.close();
+    }
+}
diff --git a/luni/src/test/java/libcore/java/net/URLConnectionTest.java b/luni/src/test/java/libcore/java/net/URLConnectionTest.java
index aecc1ad..3492193 100644
--- a/luni/src/test/java/libcore/java/net/URLConnectionTest.java
+++ b/luni/src/test/java/libcore/java/net/URLConnectionTest.java
@@ -26,6 +26,9 @@
 import com.google.mockwebserver.RecordedRequest;
 import com.google.mockwebserver.SocketPolicy;
 
+import java.lang.reflect.Field;
+import java.net.ContentHandler;
+import java.net.ContentHandlerFactory;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
@@ -2970,6 +2973,59 @@
         connection.disconnect();
     }
 
+    @Test public void setContentHandlerFactory() throws Exception {
+        // Verify that the static ContentHandlerFactory is null
+        Field f = URLConnection.class.getDeclaredField("factory");
+        f.setAccessible(true);
+        assertNull(f.get(null));
+
+        try {
+            URLConnection.setContentHandlerFactory(new MockContentHandlerFactory());
+            String msg = "ABC";
+            server.enqueue(new MockResponse()
+                    .addHeader("Content-Type: text/plain")
+                    .setBody(msg));
+            server.enqueue(new MockResponse()
+                    .addHeader("Content-Type: " + MockContentHandlerFactory.HANDLED_MIME_TYPE)
+                    .setBody(msg));
+            server.play();
+
+            HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
+            assertEquals("text/plain", connection.getContentType());
+            assertEquals(msg, readAscii((InputStream) connection.getContent()));
+
+            connection = (HttpURLConnection) server.getUrl("/").openConnection();
+            assertEquals(MockContentHandlerFactory.HANDLED_MIME_TYPE, connection.getContentType());
+            assertEquals(MockContentHandler.CONTENT, connection.getContent());
+        } finally {
+            // reset the static ContentHandlerFactory
+            f.set(null, null);
+        }
+    }
+
+    private static class MockContentHandler extends ContentHandler {
+
+        private static final String CONTENT = "SECRET_CONTENT";
+
+        @Override
+        public Object getContent(URLConnection urlc) throws IOException {
+            return CONTENT;
+        }
+    }
+
+    private static class MockContentHandlerFactory implements ContentHandlerFactory {
+
+        private static final String HANDLED_MIME_TYPE = "text/secret";
+
+        @Override
+        public ContentHandler createContentHandler(String mimetype) {
+            if (HANDLED_MIME_TYPE.equals(mimetype)) {
+                return new MockContentHandler();
+            }
+            return null;
+        }
+    }
+
     // http://b/4361656
     @Test public void urlContainsQueryButNoPath() throws Exception {
         server.enqueue(new MockResponse().setBody("A"));