diff options
Diffstat (limited to 'luni/src/test/java')
365 files changed, 13669 insertions, 68749 deletions
diff --git a/luni/src/test/java/com/android/org/bouncycastle/crypto/digests/DigestTest.java b/luni/src/test/java/com/android/org/bouncycastle/crypto/digests/DigestTest.java index d2247cf..8708214 100644 --- a/luni/src/test/java/com/android/org/bouncycastle/crypto/digests/DigestTest.java +++ b/luni/src/test/java/com/android/org/bouncycastle/crypto/digests/DigestTest.java @@ -36,7 +36,7 @@ public class DigestTest extends TestCase { * @param newDigest The new digest implementation, provided by OpenSSL */ public void doTestMessageDigest(Digest oldDigest, Digest newDigest) { - final int ITERATIONS = 10; + final int ITERATIONS = 100; byte[] data = new byte[1024]; diff --git a/luni/src/test/java/com/android/org/bouncycastle/jce/provider/CertBlacklistTest.java b/luni/src/test/java/com/android/org/bouncycastle/jce/provider/CertBlacklistTest.java index 6d033d3..1475a63 100644 --- a/luni/src/test/java/com/android/org/bouncycastle/jce/provider/CertBlacklistTest.java +++ b/luni/src/test/java/com/android/org/bouncycastle/jce/provider/CertBlacklistTest.java @@ -109,6 +109,24 @@ public class CertBlacklistTest extends TestCase { "3xQAyMuOHm72exJljYFqIsiNvGE0KufCqCuH1PD97IXMrLlwGmKKg5jP349lySBpJjm6RDqCTT+6" + "dUl2jkVbeNmco99Y7AOdtLsOdXBMCo5x8lK8zwQWFrzEms0joHXCpWfGWA=="; + public static final String ANSSI = "" + + "MIIDbDCCAlSgAwIBAgIDAx2nMA0GCSqGSIb3DQEBBQUAMEsxCzAJBgNVBAYTAkZSMQ4wDAYDVQQK" + + "EwVER1RQRTEsMCoGA1UEAxMjQUMgREdUUEUgU2lnbmF0dXJlIEF1dGhlbnRpZmljYXRpb24wHhcN" + + "MTMwNzE4MTAwNTI4WhcNMTQwNzE4MTAwNTI4WjA+MQswCQYDVQQGEwJGUjETMBEGA1UECgwKREcg" + + "VHLDqXNvcjEaMBgGA1UEAwwRQUMgREcgVHLDqXNvciBTU0wwggEiMA0GCSqGSIb3DQEBAQUAA4IB" + + "DwAwggEKAoIBAQDI0WFSUyY+MmtFkqFjTefoFyDgh9b1C/2YvSIvT8oCH62JWT5rpeTCZwaXbqWc" + + "jaNfzggqaFsokqfhBif43HNHNtNJmvKE32VcuLB0SpsLR/1VeTd9F99C1JeHVa+nelumOHEfouX8" + + "rRFrxNXNIYTVeiENT8Y2YqRb/XAril9g7i674uFzLiNR/t/N/F8Exujv9U8m8rmgud/+tG9WDRaD" + + "Jwoj3ZFCOnL5qLnSUEcS6TzWpozLmC2JVO5GZKGGd7qC9FjdBkVilkbVIEGSrYvz2Uz2v5IGqMBI" + + "QaFL/kSYWxGTaedTOk2drFEApp9AEPTfv1NwCWBfegsGQrHUROM3AgMBAAGjZjBkMBIGA1UdEwEB" + + "/wQIMAYBAf8CAQQwHQYDVR0OBBYEFAAMW8lJqJW0DtAv5p3Mjogxvh9lMB8GA1UdIwQYMBaAFOnb" + + "kI/9W5nkFTvwYlyn5A1Y6IeZMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQUFAAOCAQEAtDfG" + + "HkHOLW2d9fiMtwtkEwDauISJLJyCjoRmawzmQbIZXq7HaLliVfE0sdfKUm0iQ0im1/CpnJLPoTeK" + + "yBHvNu1ubLc2m+9dabAYhF3pVdKC+gNaAzBXZ9Gt0p1CLk1lf8Hg+R10HN2IPCv7V/crz2Ga+c23" + + "4P3pfwYW8+Nd7alGCuvqot6UYXOlheF7zWUkHn6z6tvY+9oMDHKSUAthhA/FB50JgJU89zyTv1eg" + + "Y3ldKwvYBW3W3yNZdTHbPyNsPJdhqA55mDNsteE5YTp1PyySDb1MSVrbxDEruoH6ZE99Hob4Ih8A" + + "mn7MHZatGClECgjXWFZ2Gxa7OUCaQpcH8g=="; + public CertBlacklistTest() throws IOException { tmpFile = File.createTempFile("test", ""); DEFAULT_PUBKEYS = getDefaultPubkeys(); @@ -415,6 +433,20 @@ public class CertBlacklistTest extends TestCase { assertEquals(bl.isPublicKeyBlackListed(pk), true); } + public void testANSSISerialBlacklist() throws Exception { + CertBlacklist bl = new CertBlacklist(); + assertEquals(bl.isSerialNumberBlackListed(createSerialNumber(ANSSI)), true); + } + + public void testANSSIIntermediatePubkeyBlacklist() throws Exception { + // build the public key + PublicKey pk = createPublicKey(ANSSI); + // set our blacklist path + CertBlacklist bl = new CertBlacklist(); + // check to make sure it isn't blacklisted + assertEquals(bl.isPublicKeyBlackListed(pk), true); + } + private static void printHash(String cert) throws Exception { System.out.println("CERTIFICATE PUBLIC KEY HASH: " + getHash(createPublicKey(cert))); } diff --git a/luni/src/test/java/dalvik/system/DexClassLoaderTest.java b/luni/src/test/java/dalvik/system/DexClassLoaderTest.java index 5133ea0..c57db71 100644 --- a/luni/src/test/java/dalvik/system/DexClassLoaderTest.java +++ b/luni/src/test/java/dalvik/system/DexClassLoaderTest.java @@ -16,6 +16,7 @@ package dalvik.system; +import java.io.FilenameFilter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.io.File; @@ -29,121 +30,131 @@ import junit.framework.TestCase; * Tests for the class {@link DexClassLoader}. */ public class DexClassLoaderTest extends TestCase { - private static final File TMP_DIR = - new File(System.getProperty("java.io.tmpdir"), "loading-test"); private static final String PACKAGE_PATH = "dalvik/system/"; - private static final String JAR_NAME = "loading-test.jar"; - private static final String DEX_NAME = "loading-test.dex"; - private static final String JAR2_NAME = "loading-test2.jar"; - private static final String DEX2_NAME = "loading-test2.dex"; - private static final File JAR_FILE = new File(TMP_DIR, JAR_NAME); - private static final File DEX_FILE = new File(TMP_DIR, DEX_NAME); - private static final File JAR2_FILE = new File(TMP_DIR, JAR2_NAME); - private static final File DEX2_FILE = new File(TMP_DIR, DEX2_NAME); - private static final File OPTIMIZED_DIR = new File(TMP_DIR, "optimized"); - private static enum Configuration { - /** just one classpath element, a raw dex file */ - ONE_DEX(1), + private File srcDir; + private File dex1; + private File dex2; + private File jar1; + private File jar2; + private File optimizedDir; - /** just one classpath element, a jar file */ - ONE_JAR(1), + protected void setUp() throws Exception { + srcDir = File.createTempFile("src", ""); + assertTrue(srcDir.delete()); + assertTrue(srcDir.mkdirs()); - /** two classpath elements, both raw dex files */ - TWO_DEX(2), + dex1 = new File(srcDir, "loading-test.dex"); + dex2 = new File(srcDir, "loading-test2.dex"); + jar1 = new File(srcDir, "loading-test.jar"); + jar2 = new File(srcDir, "loading-test2.jar"); - /** two classpath elements, both jar files */ - TWO_JAR(2); + copyResource("loading-test.dex", dex1); + copyResource("loading-test2.dex", dex2); + copyResource("loading-test.jar", jar1); + copyResource("loading-test2.jar", jar2); - public final int expectedFiles; - - Configuration(int expectedFiles) { - this.expectedFiles = expectedFiles; - } + optimizedDir = File.createTempFile("optimized", ""); + assertTrue(optimizedDir.delete()); + assertTrue(optimizedDir.mkdirs()); } - protected void setUp() throws IOException { - TMP_DIR.mkdirs(); - - ClassLoader cl = DexClassLoaderTest.class.getClassLoader(); - copyResource(cl, JAR_NAME, JAR_FILE); - copyResource(cl, DEX_NAME, DEX_FILE); - copyResource(cl, JAR2_NAME, JAR2_FILE); - copyResource(cl, DEX2_NAME, DEX2_FILE); + protected void tearDown() { + cleanUpDir(srcDir); + cleanUpDir(optimizedDir); + } - OPTIMIZED_DIR.mkdirs(); - File[] files = OPTIMIZED_DIR.listFiles(); + private static void cleanUpDir(File dir) { + if (!dir.isDirectory()) { + return; + } + File[] files = dir.listFiles(); for (File file : files) { - file.delete(); + assertTrue(file.delete()); } } /** * Copy a resource in the package directory to the indicated - * target file, but only if the target file doesn't exist. + * target file. */ - private static void copyResource(ClassLoader loader, String resourceName, + private static void copyResource(String resourceName, File destination) throws IOException { - if (destination.exists()) { - return; + ClassLoader loader = DexClassLoaderTest.class.getClassLoader(); + assertFalse(destination.exists()); + InputStream in = loader.getResourceAsStream(PACKAGE_PATH + resourceName); + if (in == null) { + throw new IllegalStateException("Resource not found: " + PACKAGE_PATH + resourceName); } - InputStream in = - loader.getResourceAsStream(PACKAGE_PATH + resourceName); - FileOutputStream out = new FileOutputStream(destination); - Streams.copy(in, out); - in.close(); - out.close(); + try (FileOutputStream out = new FileOutputStream(destination)) { + Streams.copy(in, out); + } finally { + in.close(); + } } + static final FilenameFilter DEX_FILE_NAME_FILTER = new FilenameFilter() { + @Override + public boolean accept(File file, String s) { + return s.endsWith(".dex"); + } + }; + /** - * Helper to construct an instance to test. + * Helper to construct a DexClassLoader instance to test. * - * @param config how to configure the classpath + * @param files The .dex or .jar files to use for the class path. */ - private static DexClassLoader createInstance(Configuration config) { - File file1; - File file2; - - switch (config) { - case ONE_DEX: file1 = DEX_FILE; file2 = null; break; - case ONE_JAR: file1 = JAR_FILE; file2 = null; break; - case TWO_DEX: file1 = DEX_FILE; file2 = DEX2_FILE; break; - case TWO_JAR: file1 = JAR_FILE; file2 = JAR2_FILE; break; - default: throw new AssertionError("shouldn't happen"); + private ClassLoader createLoader(File... files) { + assertNotNull(files); + assertTrue(files.length > 0); + String path = files[0].getAbsolutePath(); + for (int i = 1; i < files.length; i++) { + path += File.pathSeparator + files[i].getAbsolutePath(); } - - String path = file1.getAbsolutePath(); - if (file2 != null) { - path += File.pathSeparator + file2.getAbsolutePath(); - } - - return new DexClassLoader( - path, OPTIMIZED_DIR.getAbsolutePath(), null, + return new DexClassLoader(path, optimizedDir.getAbsolutePath(), null, ClassLoader.getSystemClassLoader()); } /** - * Helper to construct an instance to test, using the jar file as - * the source, and call a named no-argument static method on a - * named class. + * Helper to construct a new DexClassLoader instance to test, using the + * given files as the class path, and call a named no-argument static + * method on a named class. * - * @param config how to configure the classpath + * @param className The name of the class of the method to call. + * @param methodName The name of the method to call. + * @param files The .dex or .jar files to use for the class path. */ - public static Object createInstanceAndCallStaticMethod( - Configuration config, String className, String methodName) - throws ClassNotFoundException, NoSuchMethodException, - IllegalAccessException, InvocationTargetException { - DexClassLoader dcl = createInstance(config); - Class c = dcl.loadClass(className); + public Object createLoaderAndCallMethod( + String className, String methodName, File... files) + throws ReflectiveOperationException { + ClassLoader cl = createLoader(files); + Class c = cl.loadClass(className); Method m = c.getMethod(methodName, (Class[]) null); return m.invoke(null, (Object[]) null); } - /* - * Tests that are parametric with respect to whether to use a jar - * file or a dex file as the source of the code + /** + * Helper to construct a new DexClassLoader instance to test, using the + * given files as the class path, and read the contents of the named + * resource as a String. + * + * @param resourceName The name of the resource to get. + * @param files The .dex or .jar files to use for the class path. */ + private String createLoaderAndGetResource(String resourceName, File... files) throws Exception { + ClassLoader cl = createLoader(files); + InputStream in = cl.getResourceAsStream(resourceName); + if (in == null) { + throw new IllegalStateException("Resource not found: " + resourceName); + } + + byte[] contents = Streams.readFully(in); + return new String(contents, "UTF-8"); + } + + // ONE_JAR /** * Just a trivial test of construction. This one merely makes @@ -151,23 +162,19 @@ public class DexClassLoaderTest extends TestCase { * to verify anything about the constructed instance, other than * checking for the existence of optimized dex files. */ - private static void test_init(Configuration config) { - createInstance(config); - - int expectedFiles = config.expectedFiles; - int actualFiles = OPTIMIZED_DIR.listFiles().length; - - assertEquals(expectedFiles, actualFiles); + public void test_oneJar_init() throws Exception { + ClassLoader cl = createLoader(jar1); + File[] files = optimizedDir.listFiles(DEX_FILE_NAME_FILTER); + assertNotNull(files); + assertEquals(1, files.length); } /** * Check that a class in the jar/dex file may be used successfully. In this * case, a trivial static method is called. */ - private static void test_simpleUse(Configuration config) throws Exception { - String result = (String) - createInstanceAndCallStaticMethod(config, "test.Test1", "test"); - + public void test_oneJar_simpleUse() throws Exception { + String result = (String) createLoaderAndCallMethod("test.Test1", "test", jar1); assertSame("blort", result); } @@ -176,312 +183,214 @@ public class DexClassLoaderTest extends TestCase { * that lives inside the loading-test dex/jar file. */ - private static void test_constructor(Configuration config) - throws Exception { - createInstanceAndCallStaticMethod( - config, "test.TestMethods", "test_constructor"); - } - - private static void test_callStaticMethod(Configuration config) - throws Exception { - createInstanceAndCallStaticMethod( - config, "test.TestMethods", "test_callStaticMethod"); - } - - private static void test_getStaticVariable(Configuration config) - throws Exception { - createInstanceAndCallStaticMethod( - config, "test.TestMethods", "test_getStaticVariable"); - } - - private static void test_callInstanceMethod(Configuration config) - throws Exception { - createInstanceAndCallStaticMethod( - config, "test.TestMethods", "test_callInstanceMethod"); - } - - private static void test_getInstanceVariable(Configuration config) - throws Exception { - createInstanceAndCallStaticMethod( - config, "test.TestMethods", "test_getInstanceVariable"); - } - - private static void test_diff_constructor(Configuration config) - throws Exception { - createInstanceAndCallStaticMethod( - config, "test.TestMethods", "test_diff_constructor"); - } - - private static void test_diff_callStaticMethod(Configuration config) - throws Exception { - createInstanceAndCallStaticMethod( - config, "test.TestMethods", "test_diff_callStaticMethod"); - } - - private static void test_diff_getStaticVariable(Configuration config) - throws Exception { - createInstanceAndCallStaticMethod( - config, "test.TestMethods", "test_diff_getStaticVariable"); - } - - private static void test_diff_callInstanceMethod(Configuration config) - throws Exception { - createInstanceAndCallStaticMethod( - config, "test.TestMethods", "test_diff_callInstanceMethod"); - } - - private static void test_diff_getInstanceVariable(Configuration config) - throws Exception { - createInstanceAndCallStaticMethod( - config, "test.TestMethods", "test_diff_getInstanceVariable"); - } - - /* - * These methods are all essentially just calls to the - * parametrically-defined tests above. - */ - - // ONE_JAR - - public void test_oneJar_init() throws Exception { - test_init(Configuration.ONE_JAR); - } - - public void test_oneJar_simpleUse() throws Exception { - test_simpleUse(Configuration.ONE_JAR); - } - public void test_oneJar_constructor() throws Exception { - test_constructor(Configuration.ONE_JAR); + createLoaderAndCallMethod("test.TestMethods", "test_constructor", jar1); } public void test_oneJar_callStaticMethod() throws Exception { - test_callStaticMethod(Configuration.ONE_JAR); + createLoaderAndCallMethod("test.TestMethods", "test_callStaticMethod", jar1); } public void test_oneJar_getStaticVariable() throws Exception { - test_getStaticVariable(Configuration.ONE_JAR); + createLoaderAndCallMethod("test.TestMethods", "test_getStaticVariable", jar1); } public void test_oneJar_callInstanceMethod() throws Exception { - test_callInstanceMethod(Configuration.ONE_JAR); + createLoaderAndCallMethod("test.TestMethods", "test_callInstanceMethod", jar1); } public void test_oneJar_getInstanceVariable() throws Exception { - test_getInstanceVariable(Configuration.ONE_JAR); + createLoaderAndCallMethod("test.TestMethods", "test_getInstanceVariable", jar1); } // ONE_DEX public void test_oneDex_init() throws Exception { - test_init(Configuration.ONE_DEX); + ClassLoader cl = createLoader(dex1); + File[] files = optimizedDir.listFiles(DEX_FILE_NAME_FILTER); + assertNotNull(files); + assertEquals(1, files.length); } public void test_oneDex_simpleUse() throws Exception { - test_simpleUse(Configuration.ONE_DEX); + String result = (String) createLoaderAndCallMethod("test.Test1", "test", dex1); + assertSame("blort", result); } public void test_oneDex_constructor() throws Exception { - test_constructor(Configuration.ONE_DEX); + createLoaderAndCallMethod("test.TestMethods", "test_constructor", dex1); } public void test_oneDex_callStaticMethod() throws Exception { - test_callStaticMethod(Configuration.ONE_DEX); + createLoaderAndCallMethod("test.TestMethods", "test_callStaticMethod", dex1); } public void test_oneDex_getStaticVariable() throws Exception { - test_getStaticVariable(Configuration.ONE_DEX); + createLoaderAndCallMethod("test.TestMethods", "test_getStaticVariable", dex1); } public void test_oneDex_callInstanceMethod() throws Exception { - test_callInstanceMethod(Configuration.ONE_DEX); + createLoaderAndCallMethod("test.TestMethods", "test_callInstanceMethod", dex1); } public void test_oneDex_getInstanceVariable() throws Exception { - test_getInstanceVariable(Configuration.ONE_DEX); + createLoaderAndCallMethod("test.TestMethods", "test_getInstanceVariable", dex1); } // TWO_JAR public void test_twoJar_init() throws Exception { - test_init(Configuration.TWO_JAR); + ClassLoader cl = createLoader(jar1, jar2); + File[] files = optimizedDir.listFiles(DEX_FILE_NAME_FILTER); + assertNotNull(files); + assertEquals(2, files.length); } public void test_twoJar_simpleUse() throws Exception { - test_simpleUse(Configuration.TWO_JAR); + String result = (String) createLoaderAndCallMethod("test.Test1", "test", jar1, jar2); + assertSame("blort", result); } public void test_twoJar_constructor() throws Exception { - test_constructor(Configuration.TWO_JAR); + createLoaderAndCallMethod("test.TestMethods", "test_constructor", jar1, jar2); } public void test_twoJar_callStaticMethod() throws Exception { - test_callStaticMethod(Configuration.TWO_JAR); + createLoaderAndCallMethod("test.TestMethods", "test_callStaticMethod", jar1, jar2); } public void test_twoJar_getStaticVariable() throws Exception { - test_getStaticVariable(Configuration.TWO_JAR); + createLoaderAndCallMethod("test.TestMethods", "test_getStaticVariable", jar1, jar2); } public void test_twoJar_callInstanceMethod() throws Exception { - test_callInstanceMethod(Configuration.TWO_JAR); + createLoaderAndCallMethod("test.TestMethods", "test_callInstanceMethod", jar1, jar2); } public void test_twoJar_getInstanceVariable() throws Exception { - test_getInstanceVariable(Configuration.TWO_JAR); + createLoaderAndCallMethod("test.TestMethods", "test_getInstanceVariable", jar1, jar2); } - public static void test_twoJar_diff_constructor() throws Exception { - test_diff_constructor(Configuration.TWO_JAR); + public void test_twoJar_diff_constructor() throws Exception { + createLoaderAndCallMethod("test.TestMethods", "test_diff_constructor", jar1, jar2); } - public static void test_twoJar_diff_callStaticMethod() throws Exception { - test_diff_callStaticMethod(Configuration.TWO_JAR); + public void test_twoJar_diff_callStaticMethod() throws Exception { + createLoaderAndCallMethod("test.TestMethods", "test_diff_callStaticMethod", jar1, jar2); } - public static void test_twoJar_diff_getStaticVariable() throws Exception { - test_diff_getStaticVariable(Configuration.TWO_JAR); + public void test_twoJar_diff_getStaticVariable() throws Exception { + createLoaderAndCallMethod("test.TestMethods", "test_diff_getStaticVariable", jar1, jar2); } - public static void test_twoJar_diff_callInstanceMethod() - throws Exception { - test_diff_callInstanceMethod(Configuration.TWO_JAR); + public void test_twoJar_diff_callInstanceMethod() throws Exception { + createLoaderAndCallMethod("test.TestMethods", "test_diff_callInstanceMethod", jar1, jar2); } - public static void test_twoJar_diff_getInstanceVariable() - throws Exception { - test_diff_getInstanceVariable(Configuration.TWO_JAR); + public void test_twoJar_diff_getInstanceVariable() throws Exception { + createLoaderAndCallMethod("test.TestMethods", "test_diff_getInstanceVariable", jar1, jar2); } // TWO_DEX public void test_twoDex_init() throws Exception { - test_init(Configuration.TWO_DEX); + ClassLoader cl = createLoader(dex1, dex2); + File[] files = optimizedDir.listFiles(DEX_FILE_NAME_FILTER); + assertNotNull(files); + assertEquals(2, files.length); } public void test_twoDex_simpleUse() throws Exception { - test_simpleUse(Configuration.TWO_DEX); + String result = (String) createLoaderAndCallMethod("test.Test1", "test", dex1, dex2); + assertSame("blort", result); } public void test_twoDex_constructor() throws Exception { - test_constructor(Configuration.TWO_DEX); + createLoaderAndCallMethod("test.TestMethods", "test_constructor", dex1, dex2); } public void test_twoDex_callStaticMethod() throws Exception { - test_callStaticMethod(Configuration.TWO_DEX); + createLoaderAndCallMethod("test.TestMethods", "test_callStaticMethod", dex1, dex2); } public void test_twoDex_getStaticVariable() throws Exception { - test_getStaticVariable(Configuration.TWO_DEX); + createLoaderAndCallMethod("test.TestMethods", "test_getStaticVariable", dex1, dex2); } public void test_twoDex_callInstanceMethod() throws Exception { - test_callInstanceMethod(Configuration.TWO_DEX); + createLoaderAndCallMethod("test.TestMethods", "test_callInstanceMethod", dex1, dex2); } public void test_twoDex_getInstanceVariable() throws Exception { - test_getInstanceVariable(Configuration.TWO_DEX); + createLoaderAndCallMethod("test.TestMethods", "test_getInstanceVariable", dex1, dex2); } - public static void test_twoDex_diff_constructor() throws Exception { - test_diff_constructor(Configuration.TWO_DEX); + public void test_twoDex_diff_constructor() throws Exception { + createLoaderAndCallMethod("test.TestMethods", "test_diff_constructor", dex1, dex2); } - public static void test_twoDex_diff_callStaticMethod() throws Exception { - test_diff_callStaticMethod(Configuration.TWO_DEX); + public void test_twoDex_diff_callStaticMethod() throws Exception { + createLoaderAndCallMethod("test.TestMethods", "test_diff_callStaticMethod", dex1, dex2); } - public static void test_twoDex_diff_getStaticVariable() throws Exception { - test_diff_getStaticVariable(Configuration.TWO_DEX); + public void test_twoDex_diff_getStaticVariable() throws Exception { + createLoaderAndCallMethod("test.TestMethods", "test_diff_getStaticVariable", dex1, dex2); } - public static void test_twoDex_diff_callInstanceMethod() - throws Exception { - test_diff_callInstanceMethod(Configuration.TWO_DEX); + public void test_twoDex_diff_callInstanceMethod() throws Exception { + createLoaderAndCallMethod("test.TestMethods", "test_diff_callInstanceMethod", dex1, dex2); } - public static void test_twoDex_diff_getInstanceVariable() - throws Exception { - test_diff_getInstanceVariable(Configuration.TWO_DEX); + public void test_twoDex_diff_getInstanceVariable() throws Exception { + createLoaderAndCallMethod("test.TestMethods", "test_diff_getInstanceVariable", dex1, dex2); } /* * Tests specifically for resource-related functionality. Since * raw dex files don't contain resources, these test only work - * with jar files. The first couple methods here are helpers, - * and they are followed by the tests per se. - */ - - /** - * Check that a given resource (by name) is retrievable and contains - * the given expected contents. + * with jar files. */ - private static void test_directGetResourceAsStream(Configuration config, - String resourceName, String expectedContents) - throws Exception { - DexClassLoader dcl = createInstance(config); - InputStream in = dcl.getResourceAsStream(resourceName); - byte[] contents = Streams.readFully(in); - String s = new String(contents, "UTF-8"); - - assertEquals(expectedContents, s); - } /** * Check that a resource in the jar file is retrievable and contains * the expected contents. */ - private static void test_directGetResourceAsStream(Configuration config) - throws Exception { - test_directGetResourceAsStream( - config, "test/Resource1.txt", "Muffins are tasty!\n"); + public void test_oneJar_directGetResourceAsStream() throws Exception { + String result = createLoaderAndGetResource("test/Resource1.txt", jar1); + assertEquals("Muffins are tasty!\n", result); } /** * Check that a resource in the jar file can be retrieved from * a class within that jar file. */ - private static void test_getResourceAsStream(Configuration config) - throws Exception { - createInstanceAndCallStaticMethod( - config, "test.TestMethods", "test_getResourceAsStream"); - } - - public void test_oneJar_directGetResourceAsStream() throws Exception { - test_directGetResourceAsStream(Configuration.ONE_JAR); - } - public void test_oneJar_getResourceAsStream() throws Exception { - test_getResourceAsStream(Configuration.ONE_JAR); + createLoaderAndCallMethod("test.TestMethods", "test_getResourceAsStream", jar1); } public void test_twoJar_directGetResourceAsStream() throws Exception { - test_directGetResourceAsStream(Configuration.TWO_JAR); + String result = createLoaderAndGetResource("test/Resource1.txt", jar1, jar2); + assertEquals("Muffins are tasty!\n", result); } public void test_twoJar_getResourceAsStream() throws Exception { - test_getResourceAsStream(Configuration.TWO_JAR); + createLoaderAndCallMethod("test.TestMethods", "test_getResourceAsStream", jar1, jar2); } /** * Check that a resource in the second jar file is retrievable and * contains the expected contents. */ - public void test_twoJar_diff_directGetResourceAsStream() - throws Exception { - test_directGetResourceAsStream( - Configuration.TWO_JAR, "test2/Resource2.txt", - "Who doesn't like a good biscuit?\n"); + public void test_twoJar_diff_directGetResourceAsStream() throws Exception { + String result = createLoaderAndGetResource("test2/Resource2.txt", jar1, jar2); + assertEquals("Who doesn't like a good biscuit?\n", result); } /** * Check that a resource in a jar file can be retrieved from * a class within the other jar file. */ - public void test_twoJar_diff_getResourceAsStream() - throws Exception { - createInstanceAndCallStaticMethod( - Configuration.TWO_JAR, "test.TestMethods", - "test_diff_getResourceAsStream"); + public void test_twoJar_diff_getResourceAsStream() throws Exception { + createLoaderAndCallMethod("test.TestMethods", "test_diff_getResourceAsStream", jar1, jar2); } } diff --git a/luni/src/test/java/dalvik/system/JniTest.java b/luni/src/test/java/dalvik/system/JniTest.java new file mode 100644 index 0000000..37e687d --- /dev/null +++ b/luni/src/test/java/dalvik/system/JniTest.java @@ -0,0 +1,368 @@ +/* + * Copyright (C) 2011 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 dalvik.system; + +import junit.framework.TestCase; + +/** + * Test JNI behavior + */ +public final class JniTest extends TestCase { + + static { + System.loadLibrary("javacoretests"); + } + + /** @return this argument of method */ + private native JniTest returnThis(); + /** @return class argument of method */ + private static native Class<JniTest> returnClass(); + + private native Object returnObjectArgFrom16(int arg_no, + Object o1, Object o2, Object o3, Object o4, Object o5, + Object o6, Object o7, Object o8, Object o9, Object o10, + Object o11, Object o12, Object o13, Object o14, Object o15, + Object o16); + private native boolean returnBooleanArgFrom16(int arg_no, + boolean o1, boolean o2, boolean o3, boolean o4, boolean o5, + boolean o6, boolean o7, boolean o8, boolean o9, boolean o10, + boolean o11, boolean o12, boolean o13, boolean o14, boolean o15, + boolean o16); + private native char returnCharArgFrom16(int arg_no, + char o1, char o2, char o3, char o4, char o5, + char o6, char o7, char o8, char o9, char o10, + char o11, char o12, char o13, char o14, char o15, + char o16); + private native byte returnByteArgFrom16(int arg_no, + byte o1, byte o2, byte o3, byte o4, byte o5, + byte o6, byte o7, byte o8, byte o9, byte o10, + byte o11, byte o12, byte o13, byte o14, byte o15, + byte o16); + private native short returnShortArgFrom16(int arg_no, + short o1, short o2, short o3, short o4, short o5, + short o6, short o7, short o8, short o9, short o10, + short o11, short o12, short o13, short o14, short o15, + short o16); + private native int returnIntArgFrom16(int arg_no, + int o1, int o2, int o3, int o4, int o5, + int o6, int o7, int o8, int o9, int o10, + int o11, int o12, int o13, int o14, int o15, + int o16); + private native long returnLongArgFrom16(int arg_no, + long o1, long o2, long o3, long o4, long o5, + long o6, long o7, long o8, long o9, long o10, + long o11, long o12, long o13, long o14, long o15, + long o16); + private native float returnFloatArgFrom16(int arg_no, + float o1, float o2, float o3, float o4, float o5, + float o6, float o7, float o8, float o9, float o10, + float o11, float o12, float o13, float o14, float o15, + float o16); + private native double returnDoubleArgFrom16(int arg_no, + double o1, double o2, double o3, double o4, double o5, + double o6, double o7, double o8, double o9, double o10, + double o11, double o12, double o13, double o14, double o15, + double o16); + + /** Test cases for implicit this argument */ + public void testPassingThis() { + assertEquals(this, returnThis()); + } + + /** Test cases for implicit class argument */ + public void testPassingClass() { + assertEquals(JniTest.class, returnClass()); + } + + /** Test passing object references as arguments to a native method */ + public void testPassingObjectReferences() { + final Object[] literals = {"Bradshaw", "Isherwood", "Oldknow", "Mallet", + JniTest.class, null, Integer.valueOf(0)}; + final Object[] a = new Object[16]; + // test selection from a list of object literals where the literals are all the same + for(Object literal : literals) { + for(int i = 0; i < 16; i++) { + a[i] = literal; + } + for(int i = 0; i < 16; i++) { + assertEquals(a[i], returnObjectArgFrom16(i, a[0], a[1], a[2], a[3], a[4], + a[5], a[6], a[7], a[8], a[9], a[10], + a[11], a[12], a[13], a[14], a[15])); + } + } + // test selection from a list of object literals where the literals are shuffled + for(int j = 0; j < literals.length; j++) { + for(int i = 0; i < 16; i++) { + a[i] = literals[(i + j) % literals.length]; + } + for(int i = 0; i < 16; i++) { + assertEquals(a[i], returnObjectArgFrom16(i, a[0], a[1], a[2], a[3], a[4], + a[5], a[6], a[7], a[8], a[9], a[10], + a[11], a[12], a[13], a[14], a[15])); + } + } + } + + /** Test passing booleans as arguments to a native method */ + public void testPassingBooleans() { + final boolean[] literals = {true, false, false, true}; + final boolean[] a = new boolean[16]; + // test selection from a list of object literals where the literals are all the same + for(boolean literal : literals) { + for(int i = 0; i < 16; i++) { + a[i] = literal; + } + for(int i = 0; i < 16; i++) { + assertEquals(a[i], returnBooleanArgFrom16(i, a[0], a[1], a[2], a[3], a[4], + a[5], a[6], a[7], a[8], a[9], a[10], + a[11], a[12], a[13], a[14], a[15])); + } + } + // test selection from a list of object literals where the literals are shuffled + for(int j = 0; j < literals.length; j++) { + for(int i = 0; i < 16; i++) { + a[i] = literals[(i + j) % literals.length]; + } + for(int i = 0; i < 16; i++) { + assertEquals(a[i], returnBooleanArgFrom16(i, a[0], a[1], a[2], a[3], a[4], + a[5], a[6], a[7], a[8], a[9], a[10], + a[11], a[12], a[13], a[14], a[15])); + } + } + } + + /** Test passing characters as arguments to a native method */ + public void testPassingChars() { + final char[] literals = {Character.MAX_VALUE, Character.MIN_VALUE, + Character.MAX_HIGH_SURROGATE, Character.MAX_LOW_SURROGATE, + Character.MIN_HIGH_SURROGATE, Character.MIN_LOW_SURROGATE, + 'a', 'z', 'A', 'Z', '0', '9'}; + final char[] a = new char[16]; + // test selection from a list of object literals where the literals are all the same + for(char literal : literals) { + for(int i = 0; i < 16; i++) { + a[i] = literal; + } + for(int i = 0; i < 16; i++) { + assertEquals(a[i], returnCharArgFrom16(i, a[0], a[1], a[2], a[3], a[4], + a[5], a[6], a[7], a[8], a[9], a[10], + a[11], a[12], a[13], a[14], a[15])); + } + } + // test selection from a list of object literals where the literals are shuffled + for(int j = 0; j < literals.length; j++) { + for(int i = 0; i < 16; i++) { + a[i] = literals[(i + j) % literals.length]; + } + for(int i = 0; i < 16; i++) { + assertEquals(a[i], returnCharArgFrom16(i, a[0], a[1], a[2], a[3], a[4], + a[5], a[6], a[7], a[8], a[9], a[10], + a[11], a[12], a[13], a[14], a[15])); + } + } + } + + /** Test passing bytes as arguments to a native method */ + public void testPassingBytes() { + final byte[] literals = {Byte.MAX_VALUE, Byte.MIN_VALUE, 0, -1}; + final byte[] a = new byte[16]; + // test selection from a list of object literals where the literals are all the same + for(byte literal : literals) { + for(int i = 0; i < 16; i++) { + a[i] = literal; + } + for(int i = 0; i < 16; i++) { + assertEquals(a[i], returnByteArgFrom16(i, a[0], a[1], a[2], a[3], a[4], + a[5], a[6], a[7], a[8], a[9], a[10], + a[11], a[12], a[13], a[14], a[15])); + } + } + // test selection from a list of object literals where the literals are shuffled + for(int j = 0; j < literals.length; j++) { + for(int i = 0; i < 16; i++) { + a[i] = literals[(i + j) % literals.length]; + } + for(int i = 0; i < 16; i++) { + assertEquals(a[i], returnByteArgFrom16(i, a[0], a[1], a[2], a[3], a[4], + a[5], a[6], a[7], a[8], a[9], a[10], + a[11], a[12], a[13], a[14], a[15])); + } + } + } + + /** Test passing shorts as arguments to a native method */ + public void testPassingShorts() { + final short[] literals = {Byte.MAX_VALUE, Byte.MIN_VALUE, Short.MAX_VALUE, Short.MIN_VALUE, 0, -1}; + final short[] a = new short[16]; + // test selection from a list of object literals where the literals are all the same + for(short literal : literals) { + for(int i = 0; i < 16; i++) { + a[i] = literal; + } + for(int i = 0; i < 16; i++) { + assertEquals(a[i], returnShortArgFrom16(i, a[0], a[1], a[2], a[3], a[4], + a[5], a[6], a[7], a[8], a[9], a[10], + a[11], a[12], a[13], a[14], a[15])); + } + } + // test selection from a list of object literals where the literals are shuffled + for(int j = 0; j < literals.length; j++) { + for(int i = 0; i < 16; i++) { + a[i] = literals[(i + j) % literals.length]; + } + for(int i = 0; i < 16; i++) { + assertEquals(a[i], returnShortArgFrom16(i, a[0], a[1], a[2], a[3], a[4], + a[5], a[6], a[7], a[8], a[9], a[10], + a[11], a[12], a[13], a[14], a[15])); + } + } + } + + /** Test passing ints as arguments to a native method */ + public void testPassingInts() { + final int[] literals = {Byte.MAX_VALUE, Byte.MIN_VALUE, Short.MAX_VALUE, Short.MIN_VALUE, + Integer.MAX_VALUE, Integer.MIN_VALUE, 0, -1}; + final int[] a = new int[16]; + // test selection from a list of object literals where the literals are all the same + for(int literal : literals) { + for(int i = 0; i < 16; i++) { + a[i] = literal; + } + for(int i = 0; i < 16; i++) { + assertEquals(a[i], returnIntArgFrom16(i, a[0], a[1], a[2], a[3], a[4], + a[5], a[6], a[7], a[8], a[9], a[10], + a[11], a[12], a[13], a[14], a[15])); + } + } + // test selection from a list of object literals where the literals are shuffled + for(int j = 0; j < literals.length; j++) { + for(int i = 0; i < 16; i++) { + a[i] = literals[(i + j) % literals.length]; + } + for(int i = 0; i < 16; i++) { + assertEquals(a[i], returnIntArgFrom16(i, a[0], a[1], a[2], a[3], a[4], + a[5], a[6], a[7], a[8], a[9], a[10], + a[11], a[12], a[13], a[14], a[15])); + } + } + } + + /** Test passing longs as arguments to a native method */ + public void testPassingLongs() { + final long[] literals = {Byte.MAX_VALUE, Byte.MIN_VALUE, Short.MAX_VALUE, Short.MIN_VALUE, + Integer.MAX_VALUE, Integer.MIN_VALUE, Long.MAX_VALUE, Long.MIN_VALUE, 0, -1}; + final long[] a = new long[16]; + // test selection from a list of object literals where the literals are all the same + for(long literal : literals) { + for(int i = 0; i < 16; i++) { + a[i] = literal; + } + for(int i = 0; i < 16; i++) { + assertEquals(a[i], returnLongArgFrom16(i, a[0], a[1], a[2], a[3], a[4], + a[5], a[6], a[7], a[8], a[9], a[10], + a[11], a[12], a[13], a[14], a[15])); + } + } + // test selection from a list of object literals where the literals are shuffled + for(int j = 0; j < literals.length; j++) { + for(int i = 0; i < 16; i++) { + a[i] = literals[(i + j) % literals.length]; + } + for(int i = 0; i < 16; i++) { + assertEquals(a[i], returnLongArgFrom16(i, a[0], a[1], a[2], a[3], a[4], + a[5], a[6], a[7], a[8], a[9], a[10], + a[11], a[12], a[13], a[14], a[15])); + } + } + } + + /** Test passing floats as arguments to a native method */ + public void testPassingFloats() { + final float[] literals = {Byte.MAX_VALUE, Byte.MIN_VALUE, Short.MAX_VALUE, Short.MIN_VALUE, + Integer.MAX_VALUE, Integer.MIN_VALUE, Long.MAX_VALUE, Long.MIN_VALUE, + Float.MAX_VALUE, Float.MIN_VALUE, Float.MIN_NORMAL, Float.NaN, + Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY, (float)Math.E, (float)Math.PI, 0, -1}; + final float[] a = new float[16]; + // test selection from a list of object literals where the literals are all the same + for(float literal : literals) { + for(int i = 0; i < 16; i++) { + a[i] = literal; + } + for(int i = 0; i < 16; i++) { + assertEquals(a[i], returnFloatArgFrom16(i, a[0], a[1], a[2], a[3], a[4], + a[5], a[6], a[7], a[8], a[9], a[10], + a[11], a[12], a[13], a[14], a[15])); + } + } + // test selection from a list of object literals where the literals are shuffled + for(int j = 0; j < literals.length; j++) { + for(int i = 0; i < 16; i++) { + a[i] = literals[(i + j) % literals.length]; + } + for(int i = 0; i < 16; i++) { + assertEquals(a[i], returnFloatArgFrom16(i, a[0], a[1], a[2], a[3], a[4], + a[5], a[6], a[7], a[8], a[9], a[10], + a[11], a[12], a[13], a[14], a[15])); + } + } + } + + /** Test passing doubles as arguments to a native method */ + public void testPassingDoubles() { + final double[] literals = {Byte.MAX_VALUE, Byte.MIN_VALUE, Short.MAX_VALUE, Short.MIN_VALUE, + Integer.MAX_VALUE, Integer.MIN_VALUE, Long.MAX_VALUE, Long.MIN_VALUE, + Float.MAX_VALUE, Float.MIN_VALUE, Float.MIN_NORMAL, Float.NaN, + Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY, + Double.MAX_VALUE, Double.MIN_VALUE, Double.MIN_NORMAL, Double.NaN, + Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, + Math.E, Math.PI, 0, -1}; + final double[] a = new double[16]; + // test selection from a list of object literals where the literals are all the same + for(double literal : literals) { + for(int i = 0; i < 16; i++) { + a[i] = literal; + } + for(int i = 0; i < 16; i++) { + assertEquals(a[i], returnDoubleArgFrom16(i, a[0], a[1], a[2], a[3], a[4], + a[5], a[6], a[7], a[8], a[9], a[10], + a[11], a[12], a[13], a[14], a[15])); + } + } + // test selection from a list of object literals where the literals are shuffled + for(int j = 0; j < literals.length; j++) { + for(int i = 0; i < 16; i++) { + a[i] = literals[(i + j) % literals.length]; + } + for(int i = 0; i < 16; i++) { + assertEquals(a[i], returnDoubleArgFrom16(i, a[0], a[1], a[2], a[3], a[4], + a[5], a[6], a[7], a[8], a[9], a[10], + a[11], a[12], a[13], a[14], a[15])); + } + } + } + + private static native Class<?> envGetSuperclass(Class<?> clazz); + + public void testGetSuperclass() { + assertEquals(Object.class, envGetSuperclass(String.class)); + assertEquals(null, envGetSuperclass(Object.class)); + assertEquals(null, envGetSuperclass(int.class)); + + // incorrect! the spec says this should be null. http://b/5652725 + assertEquals(Object.class, envGetSuperclass(Runnable.class)); + } +} diff --git a/luni/src/test/java/dalvik/system/VMRuntimeTest.java b/luni/src/test/java/dalvik/system/VMRuntimeTest.java new file mode 100644 index 0000000..251ecd8 --- /dev/null +++ b/luni/src/test/java/dalvik/system/VMRuntimeTest.java @@ -0,0 +1,135 @@ +/* + * Copyright (C) 2014 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 dalvik.system; + +import java.lang.reflect.Array; +import junit.framework.TestCase; + +/** + * Test VMRuntime behavior. + */ +public final class VMRuntimeTest extends TestCase { + + private void doTestNewNonMovableArray(Class<?> componentType, int step, int maxLength) { + // Can't create negative sized arrays. + try { + Object array = VMRuntime.getRuntime().newNonMovableArray(componentType, -1); + assertTrue(false); + } catch (NegativeArraySizeException expected) { + } + + try { + Object array = VMRuntime.getRuntime().newNonMovableArray(componentType, Integer.MIN_VALUE); + assertTrue(false); + } catch (NegativeArraySizeException expected) { + } + + // Allocate arrays in a loop and check their properties. + for (int i = 0; i <= maxLength; i += step) { + Object array = VMRuntime.getRuntime().newNonMovableArray(componentType, i); + assertTrue(array.getClass().isArray()); + assertEquals(array.getClass().getComponentType(), componentType); + assertEquals(Array.getLength(array), i); + } + } + + public void testNewNonMovableArray() { + // Can't create arrays with no component type. + try { + Object array = VMRuntime.getRuntime().newNonMovableArray(null, 0); + assertTrue(false); + } catch (NullPointerException expected) { + } + + // Can't create arrays of void. + try { + Object array = VMRuntime.getRuntime().newNonMovableArray(void.class, 0); + assertTrue(false); + } catch (NoClassDefFoundError expected) { + } + + int maxLengthForLoop = 16 * 1024; + int step = 67; + doTestNewNonMovableArray(boolean.class, step, maxLengthForLoop); + doTestNewNonMovableArray(byte.class, step, maxLengthForLoop); + doTestNewNonMovableArray(char.class, step, maxLengthForLoop); + doTestNewNonMovableArray(short.class, step, maxLengthForLoop); + doTestNewNonMovableArray(int.class, step, maxLengthForLoop); + doTestNewNonMovableArray(long.class, step, maxLengthForLoop); + doTestNewNonMovableArray(float.class, step, maxLengthForLoop); + doTestNewNonMovableArray(double.class, step, maxLengthForLoop); + doTestNewNonMovableArray(Object.class, step, maxLengthForLoop); + doTestNewNonMovableArray(Number.class, step, maxLengthForLoop); + doTestNewNonMovableArray(String.class, step, maxLengthForLoop); + doTestNewNonMovableArray(Runnable.class, step, maxLengthForLoop); + } + + private void doTestNewUnpaddedArray(Class<?> componentType, int step, int maxLength) { + // Can't create negative sized arrays. + try { + Object array = VMRuntime.getRuntime().newUnpaddedArray(componentType, -1); + assertTrue(false); + } catch (NegativeArraySizeException expected) { + } + + try { + Object array = VMRuntime.getRuntime().newUnpaddedArray(componentType, Integer.MIN_VALUE); + assertTrue(false); + } catch (NegativeArraySizeException expected) { + } + + // Allocate arrays in a loop and check their properties. + for (int i = 0; i <= maxLength; i += step) { + Object array = VMRuntime.getRuntime().newUnpaddedArray(componentType, i); + assertTrue(array.getClass().isArray()); + assertEquals(array.getClass().getComponentType(), componentType); + assertTrue(Array.getLength(array) >= i); + } + } + + public void testNewUnpaddedArray() { + // Can't create arrays with no component type. + try { + Object array = VMRuntime.getRuntime().newUnpaddedArray(null, 0); + assertTrue(false); + } catch (NullPointerException expected) { + } + + // Can't create arrays of void. + try { + Object array = VMRuntime.getRuntime().newUnpaddedArray(void.class, 0); + assertTrue(false); + } catch (NoClassDefFoundError expected) { + } + + int maxLengthForLoop = 16 * 1024; + int step = 67; + doTestNewUnpaddedArray(boolean.class, step, maxLengthForLoop); + doTestNewUnpaddedArray(byte.class, step, maxLengthForLoop); + doTestNewUnpaddedArray(char.class, step, maxLengthForLoop); + doTestNewUnpaddedArray(short.class, step, maxLengthForLoop); + doTestNewUnpaddedArray(int.class, step, maxLengthForLoop); + doTestNewUnpaddedArray(long.class, step, maxLengthForLoop); + doTestNewUnpaddedArray(float.class, step, maxLengthForLoop); + doTestNewUnpaddedArray(double.class, step, maxLengthForLoop); + doTestNewUnpaddedArray(Object.class, step, maxLengthForLoop); + doTestNewUnpaddedArray(Number.class, step, maxLengthForLoop); + doTestNewUnpaddedArray(String.class, step, maxLengthForLoop); + doTestNewUnpaddedArray(Runnable.class, step, maxLengthForLoop); + } +} + diff --git a/luni/src/test/java/libcore/android/system/OsConstantsTest.java b/luni/src/test/java/libcore/android/system/OsConstantsTest.java new file mode 100644 index 0000000..681d68c --- /dev/null +++ b/luni/src/test/java/libcore/android/system/OsConstantsTest.java @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2014 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.system; + +import junit.framework.TestCase; + +public class OsConstantsTest extends TestCase { + + // http://b/15602893 + public void testBug15602893() { + assertTrue(OsConstants.RT_SCOPE_HOST > 0); + assertTrue(OsConstants.RT_SCOPE_LINK > 0); + assertTrue(OsConstants.RT_SCOPE_SITE > 0); + + assertTrue(OsConstants.IFA_F_TENTATIVE > 0); + } +} diff --git a/luni/src/test/java/libcore/icu/AlphabeticIndexTest.java b/luni/src/test/java/libcore/icu/AlphabeticIndexTest.java index 801db4b..6c7452d 100644 --- a/luni/src/test/java/libcore/icu/AlphabeticIndexTest.java +++ b/luni/src/test/java/libcore/icu/AlphabeticIndexTest.java @@ -20,8 +20,7 @@ import java.util.Locale; public class AlphabeticIndexTest extends junit.framework.TestCase { private static AlphabeticIndex.ImmutableIndex createIndex(Locale locale) { - return new AlphabeticIndex(locale).addLabels(Locale.US) - .getImmutableIndex(); + return new AlphabeticIndex(locale).addLabels(Locale.US).getImmutableIndex(); } private static void assertHasLabel(AlphabeticIndex.ImmutableIndex ii, String string, String expectedLabel) { @@ -51,8 +50,10 @@ public class AlphabeticIndexTest extends junit.framework.TestCase { // Kanji (sorts to inflow section) assertHasLabel(ja, "\u65e5", ""); + // http://bugs.icu-project.org/trac/ticket/10423 / http://b/10809397 assertHasLabel(ja, "\u95c7", ""); + assertHasLabel(ja, "\u308f", "わ"); // English assertHasLabel(ja, "Smith", "S"); @@ -106,12 +107,13 @@ public class AlphabeticIndexTest extends junit.framework.TestCase { } public void test_de() throws Exception { - // German: [A-S,Sch,St,T-Z] (no ß or umlauted characters in standard alphabet) + // German: [A-Z] (no ß or umlauted characters in standard alphabet) AlphabeticIndex.ImmutableIndex de = createIndex(Locale.GERMAN); assertHasLabel(de, "ßind", "S"); + // We no longer split out "S", "Sch", and "St". assertHasLabel(de, "Sacher", "S"); - assertHasLabel(de, "Schiller", "Sch"); - assertHasLabel(de, "Steiff", "St"); + assertHasLabel(de, "Schiller", "S"); + assertHasLabel(de, "Steiff", "S"); } public void test_th() throws Exception { @@ -138,14 +140,19 @@ public class AlphabeticIndexTest extends junit.framework.TestCase { public void test_zh_CN() throws Exception { // Simplified Chinese (default collator Pinyin): [A-Z] - // Shen/Chen (simplified): should be, usually, 'S' for name collator and 'C' for apps/other AlphabeticIndex.ImmutableIndex zh_CN = createIndex(new Locale("zh", "CN")); // Jia/Gu: should be, usually, 'J' for name collator and 'G' for apps/other assertHasLabel(zh_CN, "\u8d3e", "J"); - // Shen/Chen - assertHasLabel(zh_CN, "\u6c88", "C"); // icu4c 50 does not specialize for names. + // Shen/Chen (simplified): should usually be 'S' for names and 'C' for apps/other. + // icu4c does not specialize for names and defaults to 'C'. + // Some OEMs prefer to default to 'S'. + // We allow either to pass CTS since neither choice is right all the time. + // assertHasLabel(zh_CN, "\u6c88", "C"); + String shenChenLabel = zh_CN.getBucketLabel(zh_CN.getBucketIndex("\u6c88")); + assertTrue(shenChenLabel.equals("C") || shenChenLabel.equals("S")); + // Shen/Chen (traditional) assertHasLabel(zh_CN, "\u700b", "S"); } diff --git a/luni/src/test/java/libcore/icu/DateIntervalFormatTest.java b/luni/src/test/java/libcore/icu/DateIntervalFormatTest.java index c8cf572..bac8138 100644 --- a/luni/src/test/java/libcore/icu/DateIntervalFormatTest.java +++ b/luni/src/test/java/libcore/icu/DateIntervalFormatTest.java @@ -16,13 +16,9 @@ package libcore.icu; -import java.util.Arrays; -import java.util.Locale; - import java.util.Calendar; -import java.util.Date; +import java.util.Locale; import java.util.TimeZone; - import static libcore.icu.DateIntervalFormat.*; public class DateIntervalFormatTest extends junit.framework.TestCase { @@ -42,6 +38,7 @@ public class DateIntervalFormatTest extends junit.framework.TestCase { c.set(Calendar.HOUR_OF_DAY, 3); c.set(Calendar.MINUTE, 30); c.set(Calendar.SECOND, 15); + c.set(Calendar.MILLISECOND, 0); long timeWithCurrentYear = c.getTimeInMillis(); c.set(Calendar.YEAR, 2009); @@ -89,26 +86,26 @@ public class DateIntervalFormatTest extends junit.framework.TestCase { assertEquals("19.01.2009 - 09.02.2012", formatDateRange(de_DE, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE)); assertEquals("1/19/2009", formatDateRange(es_US, tz, fixedTime, fixedTime + HOUR, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE)); - assertEquals("19/1/2009 – 22/1/2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE)); - assertEquals("19/1/2009 – 22/4/2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE)); - assertEquals("19/1/2009 – 9/2/2012", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE)); + assertEquals("19/1/2009–22/1/2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE)); + assertEquals("19/1/2009–22/4/2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE)); + assertEquals("19/1/2009–9/2/2012", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE)); assertEquals("19/1/2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + HOUR, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE)); - assertEquals("19/1/2009 – 22/1/2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE)); - assertEquals("19/1/2009 – 22/4/2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE)); - assertEquals("19/1/2009 – 9/2/2012", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE)); + assertEquals("19/1/2009–22/1/2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE)); + assertEquals("19/1/2009–22/4/2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE)); + assertEquals("19/1/2009–9/2/2012", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE)); // These are some random other test cases I came up with. - assertEquals("January 19–22, 2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * DAY, 0)); - assertEquals("Jan 19–22, 2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL)); + assertEquals("January 19 – 22, 2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * DAY, 0)); + assertEquals("Jan 19 – 22, 2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL)); assertEquals("Mon, Jan 19 – Thu, Jan 22, 2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL)); assertEquals("Monday, January 19 – Thursday, January 22, 2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY)); assertEquals("January 19 – April 22, 2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * MONTH, 0)); assertEquals("Jan 19 – Apr 22, 2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL)); assertEquals("Mon, Jan 19 – Wed, Apr 22, 2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL)); - assertEquals("January–April 2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_NO_MONTH_DAY)); + assertEquals("January – April 2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_NO_MONTH_DAY)); assertEquals("Jan 19, 2009 – Feb 9, 2012", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL)); assertEquals("Jan 2009 – Feb 2012", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_NO_MONTH_DAY | FORMAT_ABBREV_ALL)); @@ -135,36 +132,36 @@ public class DateIntervalFormatTest extends junit.framework.TestCase { // The same tests but for es_US. assertEquals("19–22 enero 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * DAY, 0)); - assertEquals("19–22 ene 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL)); - assertEquals("lun 19 ene – jue 22 ene 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL)); - assertEquals("lunes 19 enero – jueves 22 enero 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY)); + assertEquals("19–22 ene. 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL)); + assertEquals("lun., 19 ene.–jue., 22 ene. de 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL)); + assertEquals("lunes, 19 enero–jueves, 22 enero de 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY)); - assertEquals("19 enero – 22 abril 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH, 0)); - assertEquals("19 ene – 22 abr 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL)); - assertEquals("lun 19 ene – mié 22 abr 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL)); - assertEquals("enero–abril 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_NO_MONTH_DAY)); + assertEquals("19 enero–22 abril de 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH, 0)); + assertEquals("19 ene.–22 abr. de 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL)); + assertEquals("lun., 19 ene.–mié., 22 abr. de 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL)); + assertEquals("enero–abril de 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_NO_MONTH_DAY)); - assertEquals("19 ene 2009 – 9 feb 2012", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL)); - assertEquals("ene 2009 – feb 2012", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_NO_MONTH_DAY | FORMAT_ABBREV_ALL)); - assertEquals("19 enero 2009 – 9 febrero 2012", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR, 0)); - assertEquals("lunes 19 enero 2009 – jueves 9 febrero 2012", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_WEEKDAY)); + assertEquals("19 ene. de 2009–9 feb. de 2012", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL)); + assertEquals("ene. 2009–feb. 2012", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_NO_MONTH_DAY | FORMAT_ABBREV_ALL)); + assertEquals("19 enero de 2009–9 febrero de 2012", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR, 0)); + assertEquals("lunes, 19 enero de 2009–jueves, 9 febrero de 2012", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_WEEKDAY)); // The same tests but for es_ES. assertEquals("19–22 enero 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * DAY, 0)); - assertEquals("19–22 ene 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL)); - assertEquals("lun 19 ene – jue 22 ene 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL)); - assertEquals("lunes 19 enero – jueves 22 enero 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY)); - - assertEquals("19 enero – 22 abril 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH, 0)); - assertEquals("19 ene – 22 abr 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL)); - assertEquals("lun 19 ene – mié 22 abr 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL)); - assertEquals("enero–abril 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_NO_MONTH_DAY)); - - assertEquals("19 ene 2009 – 9 feb 2012", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL)); - assertEquals("ene 2009 – feb 2012", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_NO_MONTH_DAY | FORMAT_ABBREV_ALL)); - assertEquals("19 enero 2009 – 9 febrero 2012", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR, 0)); - assertEquals("lunes 19 enero 2009 – jueves 9 febrero 2012", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_WEEKDAY)); + assertEquals("19–22 ene. 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL)); + assertEquals("lun., 19 ene.–jue., 22 ene. de 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL)); + assertEquals("lunes, 19 enero–jueves, 22 enero de 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY)); + + assertEquals("19 enero–22 abril de 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH, 0)); + assertEquals("19 ene.–22 abr. de 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL)); + assertEquals("lun., 19 ene.–mié., 22 abr. de 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL)); + assertEquals("enero–abril de 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_NO_MONTH_DAY)); + + assertEquals("19 ene. de 2009–9 feb. de 2012", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL)); + assertEquals("ene. 2009–feb. 2012", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_NO_MONTH_DAY | FORMAT_ABBREV_ALL)); + assertEquals("19 enero de 2009–9 febrero de 2012", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR, 0)); + assertEquals("lunes, 19 enero de 2009–jueves, 9 febrero de 2012", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_WEEKDAY)); } // http://b/8862241 - we should be able to format dates past 2038. @@ -173,6 +170,7 @@ public class DateIntervalFormatTest extends junit.framework.TestCase { Locale l = Locale.US; TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles"); Calendar c = Calendar.getInstance(tz, l); + c.clear(); c.set(2042, Calendar.JANUARY, 19, 3, 30); long jan_19_2042 = c.getTimeInMillis(); c.set(2046, Calendar.OCTOBER, 4, 3, 30); @@ -221,11 +219,11 @@ public class DateIntervalFormatTest extends junit.framework.TestCase { assertEquals("4 PM", formatDateRange(l, utc, teaTime, teaTime, abbr12)); // Abbreviated on-the-hour ranges. - assertEquals("00:00–16:00", formatDateRange(l, utc, midnight, teaTime, abbr24)); + assertEquals("00:00 – 16:00", formatDateRange(l, utc, midnight, teaTime, abbr24)); assertEquals("12 AM – 4 PM", formatDateRange(l, utc, midnight, teaTime, abbr12)); // Abbreviated mixed ranges. - assertEquals("00:00–16:01", formatDateRange(l, utc, midnight, teaTime + MINUTE, abbr24)); + assertEquals("00:00 – 16:01", formatDateRange(l, utc, midnight, teaTime + MINUTE, abbr24)); assertEquals("12:00 AM – 4:01 PM", formatDateRange(l, utc, midnight, teaTime + MINUTE, abbr12)); } @@ -261,10 +259,49 @@ public class DateIntervalFormatTest extends junit.framework.TestCase { int flags = FORMAT_SHOW_TIME | FORMAT_24HOUR | FORMAT_SHOW_DATE; - assertEquals("January 1, 1970, 22:00–00:00", formatDateRange(l, utc, 22 * HOUR, 24 * HOUR, flags)); + assertEquals("January 1, 1970, 22:00 – 00:00", formatDateRange(l, utc, 22 * HOUR, 24 * HOUR, flags)); assertEquals("January 1, 1970, 22:00 – January 2, 1970, 00:30", formatDateRange(l, utc, 22 * HOUR, 24 * HOUR + 30 * MINUTE, flags)); } + // The fix for http://b/10560853 didn't work except for the day around the epoch, which was + // all the unit test checked! + public void test_single_day_events_later_than_epoch() throws Exception { + Locale l = Locale.US; + TimeZone utc = TimeZone.getTimeZone("UTC"); + + int flags = FORMAT_SHOW_TIME | FORMAT_24HOUR | FORMAT_SHOW_DATE; + + Calendar c = Calendar.getInstance(utc, l); + c.clear(); + c.set(1980, Calendar.JANUARY, 1, 0, 0); + long jan_1_1980 = c.getTimeInMillis(); + assertEquals("January 1, 1980, 22:00 – 00:00", + formatDateRange(l, utc, jan_1_1980 + 22 * HOUR, jan_1_1980 + 24 * HOUR, flags)); + assertEquals("January 1, 1980, 22:00 – January 2, 1980, 00:30", + formatDateRange(l, utc, jan_1_1980 + 22 * HOUR, jan_1_1980 + 24 * HOUR + 30 * MINUTE, flags)); + } + + // The fix for http://b/10560853 didn't work except for UTC, which was + // all the unit test checked! + public void test_single_day_events_not_in_UTC() throws Exception { + Locale l = Locale.US; + TimeZone pacific = TimeZone.getTimeZone("America/Los_Angeles"); + + int flags = FORMAT_SHOW_TIME | FORMAT_24HOUR | FORMAT_SHOW_DATE; + + Calendar c = Calendar.getInstance(pacific, l); + c.clear(); + c.set(1980, Calendar.JANUARY, 1, 0, 0); + long jan_1_1980 = c.getTimeInMillis(); + assertEquals("January 1, 1980, 22:00 – 00:00", + formatDateRange(l, pacific, jan_1_1980 + 22 * HOUR, jan_1_1980 + 24 * HOUR, flags)); + + c.set(1980, Calendar.JULY, 1, 0, 0); + long jul_1_1980 = c.getTimeInMillis(); + assertEquals("July 1, 1980, 22:00 – 00:00", + formatDateRange(l, pacific, jul_1_1980 + 22 * HOUR, jul_1_1980 + 24 * HOUR, flags)); + } + // http://b/10209343 - even if the caller didn't explicitly ask us to include the year, // we should do so for years other than the current year. public void test10209343_when_not_this_year() { @@ -347,6 +384,7 @@ public class DateIntervalFormatTest extends junit.framework.TestCase { public void test12004664() throws Exception { TimeZone utc = TimeZone.getTimeZone("UTC"); Calendar c = Calendar.getInstance(utc, Locale.US); + c.clear(); c.set(Calendar.YEAR, 1980); c.set(Calendar.MONTH, Calendar.FEBRUARY); c.set(Calendar.DAY_OF_MONTH, 10); @@ -361,9 +399,9 @@ public class DateIntervalFormatTest extends junit.framework.TestCase { // the Gregorian calendar, we want to deliberately force icu4c to agree, otherwise we'd have // a mix of calendars throughout an app's UI depending on whether Java or native code formatted // the date. - //assertEquals("یکشنبه ۲۱ بهمن ۱۳۵۸ ه.ش.", formatDateRange(new Locale("fa"), utc, thisYear, thisYear, flags)); - //assertEquals("AP ۱۳۵۸ سلواغه ۲۱, یکشنبه", formatDateRange(new Locale("ps"), utc, thisYear, thisYear, flags)); - //assertEquals("วันอาทิตย์ 10 กุมภาพันธ์ 2523", formatDateRange(new Locale("th"), utc, thisYear, thisYear, flags)); + // assertEquals("یکشنبه ۲۱ بهمن ۱۳۵۸ ه.ش.", formatDateRange(new Locale("fa"), utc, thisYear, thisYear, flags)); + // assertEquals("AP ۱۳۵۸ سلواغه ۲۱, یکشنبه", formatDateRange(new Locale("ps"), utc, thisYear, thisYear, flags)); + // assertEquals("วันอาทิตย์ 10 กุมภาพันธ์ 2523", formatDateRange(new Locale("th"), utc, thisYear, thisYear, flags)); // For now, here are the localized Gregorian strings instead... assertEquals("یکشنبه ۱۰ فوریهٔ ۱۹۸۰", formatDateRange(new Locale("fa"), utc, thisYear, thisYear, flags)); diff --git a/luni/src/test/java/libcore/icu/ICUTest.java b/luni/src/test/java/libcore/icu/ICUTest.java index b3d16f9..a7cc7a0 100644 --- a/luni/src/test/java/libcore/icu/ICUTest.java +++ b/luni/src/test/java/libcore/icu/ICUTest.java @@ -16,6 +16,8 @@ package libcore.icu; +import java.text.BreakIterator; +import java.text.Collator; import java.util.Arrays; import java.util.Locale; @@ -42,26 +44,26 @@ public class ICUTest extends junit.framework.TestCase { } public void test_getBestDateTimePattern() throws Exception { - assertEquals("d MMMM", ICU.getBestDateTimePattern("MMMMd", "ca_ES")); - assertEquals("d 'de' MMMM", ICU.getBestDateTimePattern("MMMMd", "es_ES")); - assertEquals("d. MMMM", ICU.getBestDateTimePattern("MMMMd", "de_CH")); - assertEquals("MMMM d", ICU.getBestDateTimePattern("MMMMd", "en_US")); - assertEquals("d LLLL", ICU.getBestDateTimePattern("MMMMd", "fa_IR")); - assertEquals("M月d日", ICU.getBestDateTimePattern("MMMMd", "ja_JP")); + assertEquals("d MMMM", ICU.getBestDateTimePattern("MMMMd", new Locale("ca", "ES"))); + assertEquals("d 'de' MMMM", ICU.getBestDateTimePattern("MMMMd", new Locale("es", "ES"))); + assertEquals("d. MMMM", ICU.getBestDateTimePattern("MMMMd", new Locale("de", "CH"))); + assertEquals("MMMM d", ICU.getBestDateTimePattern("MMMMd", new Locale("en", "US"))); + assertEquals("d LLLL", ICU.getBestDateTimePattern("MMMMd", new Locale("fa", "IR"))); + assertEquals("M月d日", ICU.getBestDateTimePattern("MMMMd", new Locale("ja", "JP"))); } public void test_localeFromString() throws Exception { // localeFromString is pretty lenient. Some of these can't be round-tripped // through Locale.toString. - assertEquals(Locale.ENGLISH, ICU.localeFromString("en")); - assertEquals(Locale.ENGLISH, ICU.localeFromString("en_")); - assertEquals(Locale.ENGLISH, ICU.localeFromString("en__")); - assertEquals(Locale.US, ICU.localeFromString("en_US")); - assertEquals(Locale.US, ICU.localeFromString("en_US_")); - assertEquals(new Locale("", "US", ""), ICU.localeFromString("_US")); - assertEquals(new Locale("", "US", ""), ICU.localeFromString("_US_")); - assertEquals(new Locale("", "", "POSIX"), ICU.localeFromString("__POSIX")); - assertEquals(new Locale("aa", "BB", "CC"), ICU.localeFromString("aa_BB_CC")); + assertEquals(Locale.ENGLISH, ICU.localeFromIcuLocaleId("en")); + assertEquals(Locale.ENGLISH, ICU.localeFromIcuLocaleId("en_")); + assertEquals(Locale.ENGLISH, ICU.localeFromIcuLocaleId("en__")); + assertEquals(Locale.US, ICU.localeFromIcuLocaleId("en_US")); + assertEquals(Locale.US, ICU.localeFromIcuLocaleId("en_US_")); + assertEquals(new Locale("", "US", ""), ICU.localeFromIcuLocaleId("_US")); + assertEquals(new Locale("", "US", ""), ICU.localeFromIcuLocaleId("_US_")); + assertEquals(new Locale("", "", "POSIX"), ICU.localeFromIcuLocaleId("__POSIX")); + assertEquals(new Locale("aa", "BB", "CC"), ICU.localeFromIcuLocaleId("aa_BB_CC")); } public void test_getScript_addLikelySubtags() throws Exception { @@ -72,8 +74,16 @@ public class ICUTest extends junit.framework.TestCase { assertEquals("Hebr", ICU.getScript(ICU.addLikelySubtags("iw_IL"))); } + public void test_addLikelySubtags() throws Exception { + assertEquals("Latn", ICU.addLikelySubtags(new Locale("en", "US")).getScript()); + assertEquals("Hebr", ICU.addLikelySubtags(new Locale("he")).getScript()); + assertEquals("Hebr", ICU.addLikelySubtags(new Locale("he", "IL")).getScript()); + assertEquals("Hebr", ICU.addLikelySubtags(new Locale("iw")).getScript()); + assertEquals("Hebr", ICU.addLikelySubtags(new Locale("iw", "IL")).getScript()); + } + private String best(Locale l, String skeleton) { - return ICU.getBestDateTimePattern(skeleton, l.toString()); + return ICU.getBestDateTimePattern(skeleton, l); } public void test_getDateFormatOrder() throws Exception { @@ -123,4 +133,124 @@ public class ICUTest extends junit.framework.TestCase { } catch (IllegalArgumentException expected) { } } + + public void testScriptsPassedToIcu() throws Exception { + Locale sr_Cyrl_BA = Locale.forLanguageTag("sr-Cyrl-BA"); + Locale sr_Cyrl_ME = Locale.forLanguageTag("sr-Cyrl-ME"); + Locale sr_Latn_BA = Locale.forLanguageTag("sr-Latn-BA"); + Locale sr_Latn_ME = Locale.forLanguageTag("sr-Latn-ME"); + + assertEquals("sr_BA_#Cyrl", sr_Cyrl_BA.toString()); + assertEquals("Cyrl", sr_Cyrl_BA.getScript()); + + assertEquals("sr_ME_#Cyrl", sr_Cyrl_ME.toString()); + assertEquals("Cyrl", sr_Cyrl_ME.getScript()); + + assertEquals("sr_BA_#Latn", sr_Latn_BA.toString()); + assertEquals("Latn", sr_Latn_BA.getScript()); + + assertEquals("sr_ME_#Latn", sr_Latn_ME.toString()); + assertEquals("Latn", sr_Latn_ME.getScript()); + + assertEquals("Српски", sr_Cyrl_BA.getDisplayLanguage(sr_Cyrl_BA)); + assertEquals("Босна и Херцеговина", sr_Cyrl_BA.getDisplayCountry(sr_Cyrl_BA)); + assertEquals("Ћирилица", sr_Cyrl_BA.getDisplayScript(sr_Cyrl_BA)); + assertEquals("", sr_Cyrl_BA.getDisplayVariant(sr_Cyrl_BA)); + + assertEquals("Српски", sr_Cyrl_ME.getDisplayLanguage(sr_Cyrl_ME)); + assertEquals("Црна Гора", sr_Cyrl_ME.getDisplayCountry(sr_Cyrl_ME)); + assertEquals("Ћирилица", sr_Cyrl_ME.getDisplayScript(sr_Cyrl_ME)); + assertEquals("", sr_Cyrl_ME.getDisplayVariant(sr_Cyrl_ME)); + + assertEquals("Srpski", sr_Latn_BA.getDisplayLanguage(sr_Latn_BA)); + assertEquals("Bosna i Hercegovina", sr_Latn_BA.getDisplayCountry(sr_Latn_BA)); + assertEquals("Latinica", sr_Latn_BA.getDisplayScript(sr_Latn_BA)); + assertEquals("", sr_Latn_BA.getDisplayVariant(sr_Latn_BA)); + + assertEquals("Srpski", sr_Latn_ME.getDisplayLanguage(sr_Latn_ME)); + assertEquals("Crna Gora", sr_Latn_ME.getDisplayCountry(sr_Latn_ME)); + assertEquals("Latinica", sr_Latn_ME.getDisplayScript(sr_Latn_ME)); + assertEquals("", sr_Latn_ME.getDisplayVariant(sr_Latn_ME)); + + assertEquals("BIH", sr_Cyrl_BA.getISO3Country()); + assertEquals("srp", sr_Cyrl_BA.getISO3Language()); + assertEquals("MNE", sr_Cyrl_ME.getISO3Country()); + assertEquals("srp", sr_Cyrl_ME.getISO3Language()); + assertEquals("BIH", sr_Latn_BA.getISO3Country()); + assertEquals("srp", sr_Latn_BA.getISO3Language()); + assertEquals("MNE", sr_Latn_ME.getISO3Country()); + assertEquals("srp", sr_Latn_ME.getISO3Language()); + + BreakIterator.getCharacterInstance(sr_Cyrl_BA); + BreakIterator.getCharacterInstance(sr_Cyrl_ME); + BreakIterator.getCharacterInstance(sr_Latn_BA); + BreakIterator.getCharacterInstance(sr_Latn_ME); + + BreakIterator.getLineInstance(sr_Cyrl_BA); + BreakIterator.getLineInstance(sr_Cyrl_ME); + BreakIterator.getLineInstance(sr_Latn_BA); + BreakIterator.getLineInstance(sr_Latn_ME); + + BreakIterator.getSentenceInstance(sr_Cyrl_BA); + BreakIterator.getSentenceInstance(sr_Cyrl_ME); + BreakIterator.getSentenceInstance(sr_Latn_BA); + BreakIterator.getSentenceInstance(sr_Latn_ME); + + BreakIterator.getWordInstance(sr_Cyrl_BA); + BreakIterator.getWordInstance(sr_Cyrl_ME); + BreakIterator.getWordInstance(sr_Latn_BA); + BreakIterator.getWordInstance(sr_Latn_ME); + + Collator.getInstance(sr_Cyrl_BA); + Collator.getInstance(sr_Cyrl_ME); + Collator.getInstance(sr_Latn_BA); + Collator.getInstance(sr_Latn_ME); + + Locale l = Locale.forLanguageTag("de-u-co-phonebk-kf-upper-kn"); + assertEquals("de__#u-co-phonebk-kf-upper-kn", l.toString()); + assertEquals("de-u-co-phonebk-kf-upper-kn", l.toLanguageTag()); + + Collator c = Collator.getInstance(l); + assertTrue(c.compare("2", "11") < 0); + assertTrue(c.compare("11", "ae") < 0); + assertTrue(c.compare("ae", "Ä") < 0); + assertTrue(c.compare("Ä", "ä") < 0); + assertTrue(c.compare("ä", "AF") < 0); + assertTrue(c.compare("AF", "af") < 0); + } + + // Test for the behavior of currency symbol lookup when an unrecognized locale has been set as the + // default. + public void testIcuDefaultAffectsCurrencySymbol() { + // A locale that is not going to be recognized by ICU and should fallback to "root" for the + // currency symbol. + final Locale unrecognizedLocale = new Locale("xy", "KR"); + + // A known locale with a relatively stable representation for its currency symbol. + final Locale enUsLocale = new Locale("en", "US"); + final String usDollar = "USD"; + + String initialDefaultLocale = ICU.getDefaultLocale(); + try { + // Confirm the "$" symbol for USD in en-US. + assertEquals("$", ICU.getCurrencySymbol(enUsLocale, usDollar)); + + // Set the default so this will be used as fallback for the unrecognized locale symbol lookup. + ICU.setDefaultLocale(enUsLocale.toLanguageTag()); + + // Demonstrate the USD symbol is reported as "$" for the unrecognized locale (which is using + // the default). + assertEquals("$", ICU.getCurrencySymbol(unrecognizedLocale, usDollar)); + + // Change the default. + ICU.setDefaultLocale(unrecognizedLocale.toLanguageTag()); + + String currencySymbolAfterDefaultChange = ICU.getCurrencySymbol(unrecognizedLocale, usDollar); + // "$US" is the value from root. With an unrecognized locale argument, and an unrecognized + // locale as the default, ICU has returns the value in root. + assertEquals("US$", currencySymbolAfterDefaultChange); + } finally { + ICU.setDefaultLocale(initialDefaultLocale); + } + } } diff --git a/luni/src/test/java/libcore/icu/LocaleDataTest.java b/luni/src/test/java/libcore/icu/LocaleDataTest.java index 27eda86..0a83c53 100644 --- a/luni/src/test/java/libcore/icu/LocaleDataTest.java +++ b/luni/src/test/java/libcore/icu/LocaleDataTest.java @@ -19,104 +19,116 @@ package libcore.icu; import java.util.Locale; public class LocaleDataTest extends junit.framework.TestCase { - public void testAll() throws Exception { - // Test that we can get the locale data for all known locales. - for (Locale l : Locale.getAvailableLocales()) { - LocaleData d = LocaleData.get(l); - // System.err.format("%10s %10s %10s\n", l, d.timeFormat12, d.timeFormat24); - } - } - - public void test_en_US() throws Exception { - LocaleData l = LocaleData.get(Locale.US); - assertEquals("AM", l.amPm[0]); - assertEquals("BC", l.eras[0]); - - assertEquals("January", l.longMonthNames[0]); - assertEquals("Jan", l.shortMonthNames[0]); - assertEquals("J", l.tinyMonthNames[0]); - - assertEquals("January", l.longStandAloneMonthNames[0]); - assertEquals("Jan", l.shortStandAloneMonthNames[0]); - assertEquals("J", l.tinyStandAloneMonthNames[0]); - - assertEquals("Sunday", l.longWeekdayNames[1]); - assertEquals("Sun", l.shortWeekdayNames[1]); - assertEquals("S", l.tinyWeekdayNames[1]); - - assertEquals("Sunday", l.longStandAloneWeekdayNames[1]); - assertEquals("Sun", l.shortStandAloneWeekdayNames[1]); - assertEquals("S", l.tinyStandAloneWeekdayNames[1]); - - assertEquals("Yesterday", l.yesterday); - assertEquals("Today", l.today); - assertEquals("Tomorrow", l.tomorrow); - } - - public void test_de_DE() throws Exception { - LocaleData l = LocaleData.get(new Locale("de", "DE")); - - assertEquals("Gestern", l.yesterday); - assertEquals("Heute", l.today); - assertEquals("Morgen", l.tomorrow); - } - - public void test_cs_CZ() throws Exception { - LocaleData l = LocaleData.get(new Locale("cs", "CZ")); - - assertEquals("ledna", l.longMonthNames[0]); - assertEquals("led", l.shortMonthNames[0]); - assertEquals("1", l.tinyMonthNames[0]); - - assertEquals("leden", l.longStandAloneMonthNames[0]); - assertEquals("led", l.shortStandAloneMonthNames[0]); - assertEquals("l", l.tinyStandAloneMonthNames[0]); - } - - public void test_ru_RU() throws Exception { - LocaleData l = LocaleData.get(new Locale("ru", "RU")); - - assertEquals("воскресенье", l.longWeekdayNames[1]); - assertEquals("вс", l.shortWeekdayNames[1]); - assertEquals("вс", l.tinyWeekdayNames[1]); - - // Russian stand-alone weekday names get an initial capital. - assertEquals("Воскресенье", l.longStandAloneWeekdayNames[1]); - assertEquals("Вс", l.shortStandAloneWeekdayNames[1]); - assertEquals("В", l.tinyStandAloneWeekdayNames[1]); - } - - // http://code.google.com/p/android/issues/detail?id=38844 - public void testDecimalFormatSymbols_es() throws Exception { - LocaleData es = LocaleData.get(new Locale("es")); - assertEquals(',', es.decimalSeparator); - assertEquals('.', es.groupingSeparator); - - LocaleData es_419 = LocaleData.get(new Locale("es", "419")); - assertEquals('.', es_419.decimalSeparator); - assertEquals(',', es_419.groupingSeparator); - - LocaleData es_US = LocaleData.get(new Locale("es", "US")); - assertEquals('.', es_US.decimalSeparator); - assertEquals(',', es_US.groupingSeparator); - - LocaleData es_MX = LocaleData.get(new Locale("es", "MX")); - assertEquals('.', es_MX.decimalSeparator); - assertEquals(',', es_MX.groupingSeparator); - - LocaleData es_AR = LocaleData.get(new Locale("es", "AR")); - assertEquals(',', es_AR.decimalSeparator); - assertEquals('.', es_AR.groupingSeparator); - } - - // http://b/7924970 - public void testTimeFormat12And24() throws Exception { - LocaleData en_US = LocaleData.get(Locale.US); - assertEquals("h:mm a", en_US.timeFormat12); - assertEquals("HH:mm", en_US.timeFormat24); - - LocaleData ja_JP = LocaleData.get(Locale.JAPAN); - assertEquals("aK:mm", ja_JP.timeFormat12); - assertEquals("H:mm", ja_JP.timeFormat24); + public void testAll() throws Exception { + // Test that we can get the locale data for all known locales. + for (Locale l : Locale.getAvailableLocales()) { + LocaleData d = LocaleData.get(l); + // System.err.format("%20s %s %s %s\n", l, d.yesterday, d.today, d.tomorrow); + // System.err.format("%20s %10s %10s\n", l, d.timeFormat12, d.timeFormat24); } + } + + public void test_en_US() throws Exception { + LocaleData l = LocaleData.get(Locale.US); + assertEquals("AM", l.amPm[0]); + assertEquals("a", l.narrowAm); + + assertEquals("BC", l.eras[0]); + + assertEquals("January", l.longMonthNames[0]); + assertEquals("Jan", l.shortMonthNames[0]); + assertEquals("J", l.tinyMonthNames[0]); + + assertEquals("January", l.longStandAloneMonthNames[0]); + assertEquals("Jan", l.shortStandAloneMonthNames[0]); + assertEquals("J", l.tinyStandAloneMonthNames[0]); + + assertEquals("Sunday", l.longWeekdayNames[1]); + assertEquals("Sun", l.shortWeekdayNames[1]); + assertEquals("S", l.tinyWeekdayNames[1]); + + assertEquals("Sunday", l.longStandAloneWeekdayNames[1]); + assertEquals("Sun", l.shortStandAloneWeekdayNames[1]); + assertEquals("S", l.tinyStandAloneWeekdayNames[1]); + + assertEquals("Yesterday", l.yesterday); + assertEquals("Today", l.today); + assertEquals("Tomorrow", l.tomorrow); + } + + public void test_de_DE() throws Exception { + LocaleData l = LocaleData.get(new Locale("de", "DE")); + + assertEquals("Gestern", l.yesterday); + assertEquals("Heute", l.today); + assertEquals("Morgen", l.tomorrow); + } + + public void test_cs_CZ() throws Exception { + LocaleData l = LocaleData.get(new Locale("cs", "CZ")); + + assertEquals("ledna", l.longMonthNames[0]); + assertEquals("led", l.shortMonthNames[0]); + assertEquals("1", l.tinyMonthNames[0]); + + assertEquals("leden", l.longStandAloneMonthNames[0]); + assertEquals("led", l.shortStandAloneMonthNames[0]); + assertEquals("l", l.tinyStandAloneMonthNames[0]); + } + + public void test_ko_KR() throws Exception { + LocaleData l = LocaleData.get(new Locale("ko", "KR")); + + // Ensure the fix for http://b/14493853 doesn't mangle Hangul. + assertEquals("어제", l.yesterday); + assertEquals("오늘", l.today); + assertEquals("내일", l.tomorrow); + } + + public void test_ru_RU() throws Exception { + LocaleData l = LocaleData.get(new Locale("ru", "RU")); + + assertEquals("воскресенье", l.longWeekdayNames[1]); + assertEquals("вс", l.shortWeekdayNames[1]); + assertEquals("вс", l.tinyWeekdayNames[1]); + + // Russian stand-alone weekday names get an initial capital. + assertEquals("Воскресенье", l.longStandAloneWeekdayNames[1]); + assertEquals("Вс", l.shortStandAloneWeekdayNames[1]); + assertEquals("В", l.tinyStandAloneWeekdayNames[1]); + } + + // http://code.google.com/p/android/issues/detail?id=38844 + public void testDecimalFormatSymbols_es() throws Exception { + LocaleData es = LocaleData.get(new Locale("es")); + assertEquals(',', es.decimalSeparator); + assertEquals('.', es.groupingSeparator); + + LocaleData es_419 = LocaleData.get(new Locale("es", "419")); + assertEquals('.', es_419.decimalSeparator); + assertEquals(',', es_419.groupingSeparator); + + LocaleData es_US = LocaleData.get(new Locale("es", "US")); + assertEquals('.', es_US.decimalSeparator); + assertEquals(',', es_US.groupingSeparator); + + LocaleData es_MX = LocaleData.get(new Locale("es", "MX")); + assertEquals('.', es_MX.decimalSeparator); + assertEquals(',', es_MX.groupingSeparator); + + LocaleData es_AR = LocaleData.get(new Locale("es", "AR")); + assertEquals(',', es_AR.decimalSeparator); + assertEquals('.', es_AR.groupingSeparator); + } + + // http://b/7924970 + public void testTimeFormat12And24() throws Exception { + LocaleData en_US = LocaleData.get(Locale.US); + assertEquals("h:mm a", en_US.timeFormat12); + assertEquals("HH:mm", en_US.timeFormat24); + + LocaleData ja_JP = LocaleData.get(Locale.JAPAN); + assertEquals("aK:mm", ja_JP.timeFormat12); + assertEquals("H:mm", ja_JP.timeFormat24); + } } diff --git a/luni/src/test/java/libcore/icu/NativePluralRulesTest.java b/luni/src/test/java/libcore/icu/NativePluralRulesTest.java index 73699ff..703a94a 100644 --- a/luni/src/test/java/libcore/icu/NativePluralRulesTest.java +++ b/luni/src/test/java/libcore/icu/NativePluralRulesTest.java @@ -21,7 +21,6 @@ import java.util.Locale; public class NativePluralRulesTest extends junit.framework.TestCase { public void testEnglish() throws Exception { NativePluralRules npr = NativePluralRules.forLocale(new Locale("en", "US")); - assertEquals(NativePluralRules.OTHER, npr.quantityForInt(-1)); assertEquals(NativePluralRules.OTHER, npr.quantityForInt(0)); assertEquals(NativePluralRules.ONE, npr.quantityForInt(1)); assertEquals(NativePluralRules.OTHER, npr.quantityForInt(2)); @@ -29,7 +28,6 @@ public class NativePluralRulesTest extends junit.framework.TestCase { public void testCzech() throws Exception { NativePluralRules npr = NativePluralRules.forLocale(new Locale("cs", "CZ")); - assertEquals(NativePluralRules.OTHER, npr.quantityForInt(-1)); assertEquals(NativePluralRules.OTHER, npr.quantityForInt(0)); assertEquals(NativePluralRules.ONE, npr.quantityForInt(1)); assertEquals(NativePluralRules.FEW, npr.quantityForInt(2)); @@ -40,7 +38,6 @@ public class NativePluralRulesTest extends junit.framework.TestCase { public void testArabic() throws Exception { NativePluralRules npr = NativePluralRules.forLocale(new Locale("ar")); - assertEquals(NativePluralRules.OTHER, npr.quantityForInt(-1)); assertEquals(NativePluralRules.ZERO, npr.quantityForInt(0)); assertEquals(NativePluralRules.ONE, npr.quantityForInt(1)); assertEquals(NativePluralRules.TWO, npr.quantityForInt(2)); @@ -62,6 +59,7 @@ public class NativePluralRulesTest extends junit.framework.TestCase { assertEquals(NativePluralRules.ONE, he.quantityForInt(1)); assertEquals(NativePluralRules.TWO, he.quantityForInt(2)); assertEquals(NativePluralRules.OTHER, he.quantityForInt(3)); - assertEquals(NativePluralRules.MANY, he.quantityForInt(10)); + assertEquals(NativePluralRules.OTHER, he.quantityForInt(10)); } } + diff --git a/luni/src/test/java/libcore/icu/TimeZoneNamesTest.java b/luni/src/test/java/libcore/icu/TimeZoneNamesTest.java index c2f8312..57943b0 100644 --- a/luni/src/test/java/libcore/icu/TimeZoneNamesTest.java +++ b/luni/src/test/java/libcore/icu/TimeZoneNamesTest.java @@ -59,4 +59,11 @@ public class TimeZoneNamesTest extends junit.framework.TestCase { assertTrue(TimeZoneNames.forLocale(l) != null); } } + + public void test_getExemplarLocation() throws Exception { + assertEquals("Moscow", TimeZoneNames.getExemplarLocation("en_US", "Europe/Moscow")); + assertEquals("Moskau", TimeZoneNames.getExemplarLocation("de_DE", "Europe/Moscow")); + assertEquals("Seoul", TimeZoneNames.getExemplarLocation("en_US", "Asia/Seoul")); + assertEquals("서울", TimeZoneNames.getExemplarLocation("ko_KR", "Asia/Seoul")); + } } diff --git a/luni/src/test/java/libcore/io/MemoryTest.java b/luni/src/test/java/libcore/io/MemoryTest.java index 9a596fb..c817b20 100644 --- a/luni/src/test/java/libcore/io/MemoryTest.java +++ b/luni/src/test/java/libcore/io/MemoryTest.java @@ -32,10 +32,10 @@ public class MemoryTest extends TestCase { int scale = SizeOf.INT; VMRuntime runtime = VMRuntime.getRuntime(); byte[] array = (byte[]) runtime.newNonMovableArray(byte.class, scale * values.length + 1); - int base_ptr = (int) runtime.addressOf(array); + long base_ptr = runtime.addressOf(array); for (int ptr_offset = 0; ptr_offset < 2; ++ptr_offset) { - int ptr = base_ptr + ptr_offset; // To test aligned and unaligned accesses. + long ptr = base_ptr + ptr_offset; // To test aligned and unaligned accesses. Arrays.fill(array, (byte) 0); // Regular copy. @@ -57,7 +57,7 @@ public class MemoryTest extends TestCase { } } - private void assertIntsEqual(int[] expectedValues, int ptr, boolean swap) { + private void assertIntsEqual(int[] expectedValues, long ptr, boolean swap) { for (int i = 0; i < expectedValues.length; ++i) { assertEquals(expectedValues[i], Memory.peekInt(ptr + SizeOf.INT * i, swap)); } @@ -73,10 +73,10 @@ public class MemoryTest extends TestCase { int scale = SizeOf.LONG; VMRuntime runtime = VMRuntime.getRuntime(); byte[] array = (byte[]) runtime.newNonMovableArray(byte.class, scale * values.length + 1); - int base_ptr = (int) runtime.addressOf(array); + long base_ptr = runtime.addressOf(array); for (int ptr_offset = 0; ptr_offset < 2; ++ptr_offset) { - int ptr = base_ptr + ptr_offset; // To test aligned and unaligned accesses. + long ptr = base_ptr + ptr_offset; // To test aligned and unaligned accesses. Arrays.fill(array, (byte) 0); // Regular copy. @@ -98,7 +98,7 @@ public class MemoryTest extends TestCase { } } - private void assertLongsEqual(long[] expectedValues, int ptr, boolean swap) { + private void assertLongsEqual(long[] expectedValues, long ptr, boolean swap) { for (int i = 0; i < expectedValues.length; ++i) { assertEquals(expectedValues[i], Memory.peekLong(ptr + SizeOf.LONG * i, swap)); } @@ -111,10 +111,10 @@ public class MemoryTest extends TestCase { int scale = SizeOf.SHORT; VMRuntime runtime = VMRuntime.getRuntime(); byte[] array = (byte[]) runtime.newNonMovableArray(byte.class, scale * values.length + 1); - int base_ptr = (int) runtime.addressOf(array); + long base_ptr = runtime.addressOf(array); for (int ptr_offset = 0; ptr_offset < 2; ++ptr_offset) { - int ptr = base_ptr + ptr_offset; // To test aligned and unaligned accesses. + long ptr = base_ptr + ptr_offset; // To test aligned and unaligned accesses. Arrays.fill(array, (byte) 0); // Regular copy. @@ -136,7 +136,7 @@ public class MemoryTest extends TestCase { } } - private void assertShortsEqual(short[] expectedValues, int ptr, boolean swap) { + private void assertShortsEqual(short[] expectedValues, long ptr, boolean swap) { for (int i = 0; i < expectedValues.length; ++i) { assertEquals(expectedValues[i], Memory.peekShort(ptr + SizeOf.SHORT * i, swap)); } diff --git a/luni/src/test/java/libcore/io/OsTest.java b/luni/src/test/java/libcore/io/OsTest.java index 624c119..cf28122 100644 --- a/luni/src/test/java/libcore/io/OsTest.java +++ b/luni/src/test/java/libcore/io/OsTest.java @@ -16,6 +16,7 @@ package libcore.io; +import android.system.StructUcred; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; @@ -26,8 +27,7 @@ import java.net.ServerSocket; import java.net.SocketAddress; import java.util.Locale; import junit.framework.TestCase; - -import static libcore.io.OsConstants.*; +import static android.system.OsConstants.*; public class OsTest extends TestCase { public void testIsSocket() throws Exception { diff --git a/luni/src/test/java/libcore/java/io/FileTest.java b/luni/src/test/java/libcore/java/io/FileTest.java index b2391ac..b4101f9 100644 --- a/luni/src/test/java/libcore/java/io/FileTest.java +++ b/luni/src/test/java/libcore/java/io/FileTest.java @@ -16,11 +16,9 @@ package libcore.java.io; -import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; -import java.io.InputStreamReader; import java.io.IOException; import java.util.UUID; import libcore.io.Libcore; @@ -62,7 +60,13 @@ public class FileTest extends junit.framework.TestCase { assertTrue(createDeepStructure(base).exists()); } - // readlink(2) is a special case,. + /* + * readlink(2) is a special case,. + * + * This test assumes you can create symbolic links in the temporary directory. This + * isn't true on Android if you're using /sdcard (which is used if this test is + * run using vogar). It will work in /data/data/ though. + */ public void test_longReadlink() throws Exception { File base = createTemporaryDirectory(); File target = createDeepStructure(base); @@ -144,10 +148,14 @@ public class FileTest extends junit.framework.TestCase { new MyFile(""); } - // http://b/3047893 - getCanonicalPath wasn't actually resolving symbolic links. + /* + * http://b/3047893 - getCanonicalPath wasn't actually resolving symbolic links. + * + * This test assumes you can create symbolic links in the temporary directory. This + * isn't true on Android if you're using /sdcard (which is used if this test is + * run using vogar). It will work in /data/data/ though. + */ public void test_getCanonicalPath() throws Exception { - // This assumes you can create symbolic links in the temporary directory. This isn't - // true on Android if you're using /sdcard. It will work in /data/local though. File base = createTemporaryDirectory(); File target = new File(base, "target"); target.createNewFile(); // The RI won't follow a dangling symlink, which seems like a bug! @@ -208,16 +216,13 @@ public class FileTest extends junit.framework.TestCase { } public void test_getAbsolutePath() throws Exception { - String originalUserDir = System.getProperty("user.dir"); - try { - File f = new File("poop"); - System.setProperty("user.dir", "/a"); - assertEquals("/a/poop", f.getAbsolutePath()); - System.setProperty("user.dir", "/b"); - assertEquals("/b/poop", f.getAbsolutePath()); - } finally { - System.setProperty("user.dir", originalUserDir); + String userDir = System.getProperty("user.dir"); + if (!userDir.endsWith(File.separator)) { + userDir = userDir + File.separator; } + + File f = new File("poop"); + assertEquals(userDir + "poop", f.getAbsolutePath()); } public void test_getSpace() throws Exception { diff --git a/luni/src/test/java/libcore/java/io/InterruptedStreamTest.java b/luni/src/test/java/libcore/java/io/InterruptedStreamTest.java index e5fd39f..30ae7eb 100755 --- a/luni/src/test/java/libcore/java/io/InterruptedStreamTest.java +++ b/luni/src/test/java/libcore/java/io/InterruptedStreamTest.java @@ -207,7 +207,10 @@ public final class InterruptedStreamTest extends TestCase { private static void confirmInterrupted(Thread thread) throws InterruptedException { // validate and clear interrupted bit before join - assertTrue(Thread.interrupted()); - thread.join(); + try { + assertTrue(Thread.interrupted()); + } finally { + thread.join(); + } } } diff --git a/luni/src/test/java/libcore/java/io/OldBufferedInputStreamTest.java b/luni/src/test/java/libcore/java/io/OldBufferedInputStreamTest.java deleted file mode 100644 index a3ef4e4..0000000 --- a/luni/src/test/java/libcore/java/io/OldBufferedInputStreamTest.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.io; - -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import junit.framework.TestCase; -import tests.support.Support_ASimpleInputStream; -import tests.support.Support_PlatformFile; - -public class OldBufferedInputStreamTest extends TestCase { - - public String fileName; - private BufferedInputStream is; - private FileInputStream isFile; - public String fileString = "Test_All_Tests\nTest_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_java_io_File\nTest_java_io_FileDescriptor\nTest_java_io_FileInputStream\nTest_java_io_FileNotFoundException\nTest_java_io_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n"; - - public void test_ConstructorLjava_io_InputStream() { - is = new BufferedInputStream(isFile); - - try { - is.read(); - } catch (Exception e) { - fail("Test 1: Read failed on a freshly constructed buffer."); - } - } - - public void test_ConstructorLjava_io_InputStreamI() throws IOException { - // regression test for harmony-2407 - new testBufferedInputStream(null); - assertNotNull(testBufferedInputStream.buf); - testBufferedInputStream.buf = null; - new testBufferedInputStream(null, 100); - assertNotNull(testBufferedInputStream.buf); - } - - static class testBufferedInputStream extends BufferedInputStream { - static byte[] buf; - testBufferedInputStream(InputStream is) throws IOException { - super(is); - buf = super.buf; - } - - testBufferedInputStream(InputStream is, int size) throws IOException { - super(is, size); - buf = super.buf; - } - } - - public void test_available() { - // Test for method int java.io.BufferedInputStream.available() - try { - assertTrue("Returned incorrect number of available bytes", is - .available() == fileString.length()); - } catch (IOException e) { - fail("Exception during available test"); - } - - // Test that a closed stream throws an IOE for available() - BufferedInputStream bis = new BufferedInputStream( - new ByteArrayInputStream(new byte[] { 'h', 'e', 'l', 'l', 'o', - ' ', 't', 'i', 'm' })); - int available = 0; - try { - available = bis.available(); - bis.close(); - } catch (IOException ex) { - fail(); - } - assertTrue(available != 0); - - try { - bis.available(); - fail("Expected test to throw IOE."); - } catch (IOException ex) { - // expected - } catch (Throwable ex) { - fail("Expected test to throw IOE not " - + ex.getClass().getName()); - } - } - - public void test_close() throws IOException { - is.close(); - - try { - is.read(); - fail("Test 1: IOException expected when reading after closing " + - "the stream."); - } catch (IOException e) { - // Expected. - } - - Support_ASimpleInputStream sis = new Support_ASimpleInputStream(true); - is = new BufferedInputStream(sis); - try { - is.close(); - fail("Test 2: IOException expected."); - } catch (IOException e) { - // Expected. - } - sis.throwExceptionOnNextUse = false; - } - - public void test_markI_reset() throws IOException { - byte[] buf1 = new byte[100]; - byte[] buf2 = new byte[100]; - - // Test 1: Check that reset fails if no mark has been set. - try { - is.reset(); - fail("Test 1: IOException expected if no mark has been set."); - } catch (IOException e) { - // Expected. - } - - // Test 2: Check that mark / reset works when the mark is not invalidated. - is.skip(10); - is.mark(100); - is.read(buf1, 0, buf1.length); - is.reset(); - is.read(buf2, 0, buf2.length); - is.reset(); - assertTrue("Test 2: Failed to mark correct position or reset failed.", - new String(buf1, 0, buf1.length).equals(new String(buf2, 0, buf2.length))); - - // Tests 3 and 4: Check that skipping less than readlimit bytes does - // not invalidate the mark. - is.skip(10); - try { - is.reset(); - } catch (IOException e) { - fail("Test 3: Unexpected IOException " + e.getMessage()); - } - is.read(buf2, 0, buf2.length); - is.reset(); - assertTrue("Test 4: Failed to mark correct position, or reset failed.", - new String(buf1, 0, buf1.length).equals(new String(buf2, 0, buf2.length))); - - // Test 8: Check that reset fails for a closed input stream. - is.close(); - try { - is.reset(); - fail("Test 8: IOException expected because the input stream is closed."); - } catch (IOException e) { - // Expected. - } - } - - public void test_read() throws IOException { - int c = is.read(); - assertTrue("Test 1: Incorrect character read.", - c == fileString.charAt(0)); - - byte[] bytes = new byte[256]; - for (int i = 0; i < 256; i++) { - bytes[i] = (byte) i; - } - - BufferedInputStream in = new BufferedInputStream( - new ByteArrayInputStream(bytes), 5); - - // Read more bytes than are buffered. - for (int i = 0; i < 10; i++) { - assertEquals("Test 2: Incorrect byte read;", bytes[i], in.read()); - } - - in.close(); - try { - in.read(); - fail("Test 3: IOException expected."); - } catch (IOException e) { - // Expected. - } - } - - @Override - protected void setUp() throws IOException { - fileName = System.getProperty("user.dir"); - String separator = System.getProperty("file.separator"); - if (fileName.charAt(fileName.length() - 1) == separator.charAt(0)) { - fileName = Support_PlatformFile.getNewPlatformFile(fileName, - "input.tst"); - } else { - fileName = Support_PlatformFile.getNewPlatformFile(fileName - + separator, "input.tst"); - } - OutputStream fos = new FileOutputStream(fileName); - fos.write(fileString.getBytes()); - fos.close(); - isFile = new FileInputStream(fileName); - is = new BufferedInputStream(isFile); - } - - @Override - protected void tearDown() { - try { - is.close(); - } catch (Exception e) { - } - try { - File f = new File(fileName); - f.delete(); - } catch (Exception e) { - } - } -} diff --git a/luni/src/test/java/libcore/java/io/OldFileInputStreamTest.java b/luni/src/test/java/libcore/java/io/OldFileInputStreamTest.java deleted file mode 100644 index 894849a..0000000 --- a/luni/src/test/java/libcore/java/io/OldFileInputStreamTest.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.io; - -import java.io.File; -import java.io.FileDescriptor; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.channels.FileChannel; -import junit.framework.TestCase; -import tests.support.Support_PlatformFile; - -public class OldFileInputStreamTest extends TestCase { - - public String fileName; - private FileInputStream is; - public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_java_io_File\nTest_java_io_FileDescriptor\nTest_FileInputStream\nTest_java_io_FileNotFoundException\nTest_java_io_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n"; - - public void test_ConstructorLjava_io_File() { - // Test for method FileInputStream(File) - try { - File f = new File(fileName); - is = new FileInputStream(f); - is.close(); - } catch (Exception e) { - fail("Failed to create FileInputStream : " + e.getMessage()); - } - File f2 = new File("ImprobableFile.42"); - try { - is = new FileInputStream(f2); - is.close(); - f2.delete(); - fail("FileNotFoundException expected."); - } catch (FileNotFoundException e) { - // Expected. - } catch (IOException e) { - fail("Unexpected IOException: " + e.getMessage()); - } - } - - public void test_ConstructorLjava_io_FileDescriptor() { - try { - FileInputStream fis = new FileInputStream((FileDescriptor) null); - fis.close(); - fail("NullPointerException expected."); - } catch (NullPointerException e) { - // Expected. - } catch (IOException e) { - fail("Unexpected IOException: " + e.getMessage()); - } - } - - public void test_ConstructorLjava_lang_String() { - // Test for method FileInputStream(java.lang.String) - try { - is = new FileInputStream(fileName); - is.close(); - } catch (Exception e) { - fail("Failed to create FileInputStream : " + e.getMessage()); - } - try { - is = new FileInputStream("ImprobableFile.42"); - is.close(); - new File("ImprobableFile.42").delete(); - fail("FileNotFoundException expected."); - } catch (FileNotFoundException e) { - // Expected. - } catch (IOException e) { - fail("Unexpected IOException: " + e.getMessage()); - } - } - - public void test_available() throws IOException { - is = new FileInputStream(fileName); - assertEquals("Test 1: Returned incorrect number of available bytes;", - fileString.length(), is.available()); - is.close(); - try { - is.available(); - fail("Test 2: IOException expected."); - } catch (IOException e) { - // Expected. - } - } - - public void test_getChannel() { - // Test for method FileChannel FileInputStream.getChannel() - FileChannel channel; - byte[] buffer = new byte[100]; - byte[] stringBytes; - final int offset = 5; - boolean equal = true; - - try { - FileInputStream fis = new FileInputStream(fileName); - channel = fis.getChannel(); - assertNotNull(channel); - assertTrue("Channel is closed.", channel.isOpen()); - - // Check that the channel is associated with the input stream. - channel.position(offset); - fis.read(buffer, 0, 10); - stringBytes = fileString.getBytes(); - for (int i = 0; i < 10; i++) { - equal &= (buffer[i] == stringBytes[i + offset]); - } - assertTrue("Channel is not associated with this stream.", equal); - - fis.close(); - assertFalse("Channel has not been closed.", channel.isOpen()); - } catch (FileNotFoundException e) { - fail("Could not find : " + fileName); - } - - catch (IOException e) { - fail("Exception during test : " + e.getMessage()); - } - } - - public void test_read() throws IOException { - is = new FileInputStream(fileName); - int c = is.read(); - assertEquals("Test 1: Read returned incorrect char;", - fileString.charAt(0), c); - - is.close(); - try { - is.read(); - fail("Test 2: IOException expected."); - } catch (IOException e) { - // Expected. - } - } - - public void test_read$B() throws IOException { - byte[] buf1 = new byte[100]; - is = new FileInputStream(fileName); - is.skip(3000); - is.read(buf1); - is.close(); - assertTrue("Test 1: Failed to read correct data.", - new String(buf1, 0, buf1.length).equals( - fileString.substring(3000, 3100))); - - is.close(); - try { - is.read(buf1); - fail("Test 2: IOException expected."); - } catch (IOException e) { - // Expected. - } - } - - public void test_skipJ() throws IOException { - byte[] buf1 = new byte[10]; - is = new FileInputStream(fileName); - is.skip(1000); - is.read(buf1, 0, buf1.length); - assertTrue("Test 1: Failed to skip to correct position.", - new String(buf1, 0, buf1.length).equals( - fileString.substring(1000, 1010))); - - is.close(); - try { - is.read(); - fail("Test 2: IOException expected."); - } catch (IOException e) { - // Expected. - } - } - - protected void setUp() throws Exception { - fileName = System.getProperty("java.io.tmpdir"); - String separator = System.getProperty("file.separator"); - if (fileName.charAt(fileName.length() - 1) == separator.charAt(0)) - fileName = Support_PlatformFile.getNewPlatformFile(fileName, - "input.tst"); - else - fileName = Support_PlatformFile.getNewPlatformFile(fileName - + separator, "input.tst"); - java.io.OutputStream fos = new FileOutputStream(fileName); - fos.write(fileString.getBytes()); - fos.close(); - } - - protected void tearDown() throws Exception { - if (is != null) { - is.close(); - } - new File(fileName).delete(); - } -} diff --git a/luni/src/test/java/libcore/java/io/OldFileTest.java b/luni/src/test/java/libcore/java/io/OldFileTest.java index 8265d20..07ca161 100644 --- a/luni/src/test/java/libcore/java/io/OldFileTest.java +++ b/luni/src/test/java/libcore/java/io/OldFileTest.java @@ -18,7 +18,6 @@ package libcore.java.io; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; @@ -27,16 +26,6 @@ import static tests.support.Support_Exec.execAndGetOutput; import static tests.support.Support_Exec.javaProcessBuilder; public class OldFileTest extends TestCase { - - /** Location to store tests in */ - private File tempDirectory; - - /** Temp file that does exist */ - private File tempFile; - - /** File separator */ - private String slash = File.separator; - public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_File\nTest_FileDescriptor\nTest_FileInputStream\nTest_FileNotFoundException\nTest_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n"; private static String platformId = "Android" @@ -72,76 +61,66 @@ public class OldFileTest extends TestCase { } public void test_ConstructorLjava_io_FileLjava_lang_String() throws Exception { - String error; - String dirName = System.getProperty("java.io.tmpdir"); - System.setProperty("user.dir", dirName); + String tmpDirName = System.getProperty("java.io.tmpdir"); - File d = new File(dirName); + File d = new File(tmpDirName); File f = new File(d, "input.tst"); - if (!dirName.regionMatches((dirName.length() - 1), slash, 0, 1)) - dirName += slash; - dirName += "input.tst"; - error = String.format("Test 1: Incorrect file created: %s; %s expected.", f.getPath(), dirName); - assertTrue(error, f.getPath().equals(dirName)); + + if (!tmpDirName.endsWith(File.separator)) { + tmpDirName += File.separator; + } + tmpDirName += "input.tst"; + + assertEquals(tmpDirName, f.getPath()); String fileName = null; try { f = new File(d, fileName); - fail("Test 2: NullPointerException expected."); - } catch (NullPointerException e) { + fail(); + } catch (NullPointerException expected) { } - d = null; f = new File(d, "input.tst"); - error = String.format("Test 3: Incorrect file created: %s; %s expected.", - f.getAbsolutePath(), dirName); - assertTrue(error, f.getAbsolutePath().equals(dirName)); + assertEquals(tmpDirName, f.getAbsolutePath()); // Regression test for Harmony-382 File s = null; f = new File("/abc"); d = new File(s, "/abc"); - assertEquals("Test 4: Incorrect file created;", - f.getAbsolutePath(), d.getAbsolutePath()); + assertEquals(f.getAbsolutePath(), d.getAbsolutePath()); } public void test_ConstructorLjava_lang_StringLjava_lang_String() throws IOException { - String dirName = null; - String fileName = "input.tst"; - - String userDir = System.getProperty("java.io.tmpdir"); - System.setProperty("user.dir", userDir); + String tmpDir = System.getProperty("java.io.tmpdir"); + if (!tmpDir.endsWith(File.separator)) { + tmpDir += File.separator; + } - File f = new File(dirName, fileName); - if (!userDir.regionMatches((userDir.length() - 1), slash, 0, 1)) - userDir += slash; - userDir += "input.tst"; - String error = String.format("Test 1: Incorrect file created: %s; %s expected.", - f.getAbsolutePath(), userDir); - assertTrue(error, f.getAbsolutePath().equals(userDir)); + String dirName = tmpDir; + String fileName = "input.tst"; + File f = new File(tmpDir, fileName); + tmpDir += "input.tst"; + assertEquals(tmpDir, f.getAbsolutePath()); dirName = System.getProperty("java.io.tmpdir"); fileName = null; try { f = new File(dirName, fileName); - fail("Test 2: NullPointerException expected."); - } catch (NullPointerException e) { + fail(); + } catch (NullPointerException expected) { // Expected. } fileName = "input.tst"; f = new File(dirName, fileName); - assertTrue("Test 3: Incorrect file created.", f.getPath() - .equals(userDir)); + assertEquals(tmpDir, f.getPath()); // Regression test for Harmony-382 String s = null; f = new File("/abc"); File d = new File(s, "/abc"); - assertEquals("Test 4: Incorrect file created;", d.getAbsolutePath(), f - .getAbsolutePath()); - assertEquals("Test3: Created Incorrect File", "/abc", f - .getAbsolutePath()); + assertEquals(d.getAbsolutePath(), f.getAbsolutePath()); + assertEquals("/abc", f.getAbsolutePath()); } public void test_createTempFileLjava_lang_StringLjava_lang_String() { @@ -170,8 +149,7 @@ public class OldFileTest extends TestCase { public void test_toURL3() throws MalformedURLException { File dir = new File(""); // current directory String newDirURL = dir.toURL().toString(); - assertTrue("Test 1: URL does not end with slash.", - newDirURL.endsWith("/")); + assertTrue("Test 1: URL does not end with slash.", newDirURL.endsWith(File.separator)); } public void test_deleteOnExit() throws IOException, InterruptedException { @@ -200,42 +178,4 @@ public class OldFileTest extends TestCase { assertFalse(dir.exists()); assertFalse(subDir.exists()); } - - protected void setUp() throws Exception { - super.setUp(); - - // Make sure that system properties are set correctly - String userDir = System.getProperty("java.io.tmpdir"); - if (userDir == null) - throw new Exception("System property java.io.tmpdir not defined."); - System.setProperty("java.io.tmpdir", userDir); - - /** Setup the temporary directory */ - if (!userDir.regionMatches((userDir.length() - 1), slash, 0, 1)) - userDir += slash; - tempDirectory = new File(userDir + "tempDir" - + String.valueOf(System.currentTimeMillis())); - if (!tempDirectory.mkdir()) - System.out.println("Setup for OldFileTest failed (1)."); - - /** Setup the temporary file */ - tempFile = new File(tempDirectory, "tempfile"); - FileOutputStream tempStream; - try { - tempStream = new FileOutputStream(tempFile.getPath(), false); - tempStream.close(); - } catch (IOException e) { - System.out.println("Setup for OldFileTest failed (2)."); - return; - } - } - - protected void tearDown() { - if (tempFile.exists() && !tempFile.delete()) - System.out - .println("OldFileTest.tearDown() failed, could not delete file!"); - if (!tempDirectory.delete()) - System.out - .println("OldFileTest.tearDown() failed, could not delete directory!"); - } } diff --git a/luni/src/test/java/libcore/java/io/OldFilterInputStreamTest.java b/luni/src/test/java/libcore/java/io/OldFilterInputStreamTest.java index 848b1bf..11c0279 100644 --- a/luni/src/test/java/libcore/java/io/OldFilterInputStreamTest.java +++ b/luni/src/test/java/libcore/java/io/OldFilterInputStreamTest.java @@ -18,11 +18,11 @@ package libcore.java.io; import java.io.BufferedInputStream; +import java.io.File; import java.io.FilterInputStream; import java.io.IOException; import java.util.Arrays; import tests.support.Support_ASimpleInputStream; -import tests.support.Support_PlatformFile; public class OldFilterInputStreamTest extends junit.framework.TestCase { @@ -36,13 +36,11 @@ public class OldFilterInputStreamTest extends junit.framework.TestCase { private FilterInputStream is; - byte[] ibuf = new byte[4096]; - - private static final String testString = "Lorem ipsum dolor sit amet,\n" + + private static final String INPUT = "Lorem ipsum dolor sit amet,\n" + "consectetur adipisicing elit,\nsed do eiusmod tempor incididunt ut" + "labore et dolore magna aliqua.\n"; - private static final int testLength = testString.length(); + private static final int INPUT_LENGTH = INPUT.length(); public void test_Constructor() { // The FilterInputStream object has already been created in setUp(). @@ -59,7 +57,7 @@ public class OldFilterInputStreamTest extends junit.framework.TestCase { public void test_available() throws IOException { assertEquals("Test 1: Returned incorrect number of available bytes;", - testLength, is.available()); + INPUT_LENGTH, is.available()); is.close(); try { @@ -144,7 +142,7 @@ public class OldFilterInputStreamTest extends junit.framework.TestCase { public void test_read() throws IOException { int c = is.read(); assertEquals("Test 1: Read returned incorrect char;", - testString.charAt(0), c); + INPUT.charAt(0), c); is.close(); try { @@ -161,7 +159,7 @@ public class OldFilterInputStreamTest extends junit.framework.TestCase { is.read(buf1); assertTrue("Test 1: Failed to read correct data.", new String(buf1, 0, buf1.length).equals( - testString.substring(0, 100))); + INPUT.substring(0, 100))); is.close(); try { @@ -281,7 +279,7 @@ public class OldFilterInputStreamTest extends junit.framework.TestCase { is.read(buf1, 0, buf1.length); assertTrue("Test 1: Failed to skip to the correct position.", new String(buf1, 0, buf1.length).equals( - testString.substring(10, 20))); + INPUT.substring(10, 20))); is.close(); try { @@ -292,32 +290,19 @@ public class OldFilterInputStreamTest extends junit.framework.TestCase { } } - protected void setUp() { - try { - fileName = System.getProperty("java.io.tmpdir"); - String separator = System.getProperty("file.separator"); - if (fileName.charAt(fileName.length() - 1) == separator.charAt(0)) - fileName = Support_PlatformFile.getNewPlatformFile(fileName, - "input.tst"); - else - fileName = Support_PlatformFile.getNewPlatformFile(fileName - + separator, "input.tst"); - java.io.OutputStream fos = new java.io.FileOutputStream(fileName); - fos.write(testString.getBytes()); - fos.close(); - is = new MyFilterInputStream(new java.io.FileInputStream(fileName)); - } catch (java.io.IOException e) { - System.out.println("Exception during setup"); - e.printStackTrace(); - } + protected void setUp() throws Exception { + File f = File.createTempFile("OldFilterInputStreamTest", "tst"); + fileName = f.getAbsolutePath(); + java.io.OutputStream fos = new java.io.FileOutputStream(fileName); + fos.write(INPUT.getBytes()); + fos.close(); + is = new MyFilterInputStream(new java.io.FileInputStream(fileName)); } protected void tearDown() { try { is.close(); - } catch (Exception e) { - System.out.println("Unexpected exception in tearDown()."); + } catch (Exception ignored) { } - new java.io.File(fileName).delete(); } } diff --git a/luni/src/test/java/libcore/java/io/SerializationTest.java b/luni/src/test/java/libcore/java/io/SerializationTest.java index 32bc402..03e7d94 100644 --- a/luni/src/test/java/libcore/java/io/SerializationTest.java +++ b/luni/src/test/java/libcore/java/io/SerializationTest.java @@ -49,7 +49,9 @@ public final class SerializationTest extends TestCase { static class FieldMadeTransient implements Serializable { private static final long serialVersionUID = 0L; + @SuppressWarnings("unused") private transient int transientInt; + @SuppressWarnings("unused") private int nonTransientInt; } @@ -64,7 +66,7 @@ public final class SerializationTest extends TestCase { + "374244669656c644d6164655374617469630000000000000000020001490009737461746963496e7" + "47870000022b8"; FieldMadeStatic deserialized = (FieldMadeStatic) SerializationTester.deserializeHex(s); - // The field data is simply ignored if it is static. + // The field data must be ignored if it is static. assertEquals(9999, deserialized.staticInt); } @@ -74,73 +76,101 @@ public final class SerializationTest extends TestCase { private static int staticInt = 9999; } + public static boolean serializableContainer1InitializedFlag = false; + public static boolean unserializable1InitializedFlag = false; + + public static class Unserializable1 { + static { + SerializationTest.unserializable1InitializedFlag = true; + } + } + + static class SerializableContainer1 implements Serializable { + private static final long serialVersionUID = 0L; + private Unserializable1 unserializable = null; + + static { + serializableContainer1InitializedFlag = true; + } + } + // We can serialize an object that has an unserializable field providing it is null. public void testDeserializeNullUnserializableField() throws Exception { // This was created by creating a new SerializableContainer and not setting the // unserializable field. A canned serialized form is used so we can tell if the static // initializers were executed during deserialization. - // SerializationTester.serializeHex(new SerializableContainer()); - String s = "aced0005737200376c6962636f72652e6a6176612e696f2e53657269616c697a6174696f6e54657" - + "3742453657269616c697a61626c65436f6e7461696e657200000000000000000200014c000e756e7" - + "3657269616c697a61626c657400334c6c6962636f72652f6a6176612f696f2f53657269616c697a6" - + "174696f6e546573742457617353657269616c697a61626c653b787070"; + // SerializationTester.serializeHex(new SerializableContainer1()); + String s = "aced0005737200386c6962636f72652e6a6176612e696f2e53657269616c697a6174696f6e54657" + + "3742453657269616c697a61626c65436f6e7461696e65723100000000000000000200014c000e7" + + "56e73657269616c697a61626c657400124c6a6176612f6c616e672f4f626a6563743b787070"; - serializableContainerInitializedFlag = false; - wasSerializableInitializedFlag = false; + assertFalse(serializableContainer1InitializedFlag); + assertFalse(unserializable1InitializedFlag); - SerializableContainer sc = (SerializableContainer) SerializationTester.deserializeHex(s); + SerializableContainer1 sc = (SerializableContainer1) SerializationTester.deserializeHex(s); assertNull(sc.unserializable); // Confirm the container was initialized, but the class for the null field was not. - assertTrue(serializableContainerInitializedFlag); - assertFalse(wasSerializableInitializedFlag); + assertTrue(serializableContainer1InitializedFlag); + assertFalse(unserializable1InitializedFlag); } - public static boolean serializableContainerInitializedFlag = false; + static class Unserializable2 { + } - static class SerializableContainer implements Serializable { + static class HasUnserializableField implements Serializable { private static final long serialVersionUID = 0L; - private Object unserializable = null; - - static { - serializableContainerInitializedFlag = true; - } + @SuppressWarnings("unused") // Required to make objects unserializable. + private Unserializable2 unserializable = new Unserializable2(); } // We must not serialize an object that has a non-null unserializable field. public void testSerializeUnserializableField() throws Exception { - SerializableContainer sc = new SerializableContainer(); - sc.unserializable = new WasSerializable(); + HasUnserializableField uf = new HasUnserializableField(); try { - SerializationTester.serializeHex(sc); + SerializationTester.serializeHex(uf); fail(); } catch (NotSerializableException expected) { } } + public static boolean serializableContainer2InitializedFlag = false; + + @SuppressWarnings("unused") // Required for deserialization test + static class SerializableContainer2 implements Serializable { + private static final long serialVersionUID = 0L; + private WasSerializable unserializable = null; + + static { + serializableContainer2InitializedFlag = true; + } + } + // It must not be possible to deserialize an object if a field is no longer serializable. public void testDeserializeUnserializableField() throws Exception { - // This was generated by creating a SerializableContainer and setting the unserializable + // This was generated by creating a SerializableContainer2 and setting the unserializable // field to a WasSerializable when it was still Serializable. A canned serialized form is // used so we can tell if the static initializers were executed during deserialization. - // SerializableContainer sc = new SerializableContainer(); + // SerializableContainer2 sc = new SerializableContainer2(); // sc.unserializable = new WasSerializable(); // SerializationTester.serializeHex(sc); - String s = "aced0005737200376c6962636f72652e6a6176612e696f2e53657269616c697a6174696f6e54657" - + "3742453657269616c697a61626c65436f6e7461696e657200000000000000000200014c000e756e7" - + "3657269616c697a61626c657400124c6a6176612f6c616e672f4f626a6563743b7870737200316c6" - + "962636f72652e6a6176612e696f2e53657269616c697a6174696f6e5465737424576173536572696" - + "16c697a61626c65000000000000000002000149000169787000000000"; - - serializableContainerInitializedFlag = false; - wasSerializableInitializedFlag = false; + String s = "aced0005737200386c6962636f72652e6a6176612e696f2e53657269616c697a6174696f6e54657" + + "3742453657269616c697a61626c65436f6e7461696e65723200000000000000000200014c000e7" + + "56e73657269616c697a61626c657400334c6c6962636f72652f6a6176612f696f2f53657269616" + + "c697a6174696f6e546573742457617353657269616c697a61626c653b7870737200316c6962636" + + "f72652e6a6176612e696f2e53657269616c697a6174696f6e546573742457617353657269616c6" + + "97a61626c65000000000000000002000149000169787000000000"; + + assertFalse(serializableContainer2InitializedFlag); + assertFalse(wasSerializableInitializedFlag); try { SerializationTester.deserializeHex(s); fail(); } catch (InvalidClassException expected) { } - // Confirm neither the container nor the contained class was initialized. - assertFalse(serializableContainerInitializedFlag); + // The container class will be initialized to establish the serialVersionUID. + assertTrue(serializableContainer2InitializedFlag); + // Confirm the contained class was initialized. assertFalse(wasSerializableInitializedFlag); } @@ -196,7 +226,7 @@ public final class SerializationTest extends TestCase { + "e546573742457617353657269616c697a61626c65000000000000000002000149000169787000000" + "000"; - wasSerializableInitializedFlag = false; + assertFalse(wasSerializableInitializedFlag); try { SerializationTester.deserializeHex(s); fail(); @@ -239,7 +269,7 @@ public final class SerializationTest extends TestCase { final String s = "aced0005737200336c6962636f72652e6a6176612e696f2e53657269616c697a6174696f6" + "e546573742457617345787465726e616c697a61626c6500000000000000000c0000787078"; - wasExternalizableInitializedFlag = false; + assertFalse(wasExternalizableInitializedFlag); try { SerializationTester.deserializeHex(s); fail(); @@ -275,7 +305,7 @@ public final class SerializationTest extends TestCase { + "e5465737424576173456e756d00000000000000001200007872000e6a6176612e6c616e672e456e7" + "56d0000000000000000120000787074000556414c5545"; - wasEnumInitializedFlag = false; + assertFalse(wasEnumInitializedFlag); try { SerializationTester.deserializeHex(s); fail(); @@ -309,7 +339,7 @@ public final class SerializationTest extends TestCase { final String s = "aced00057372002b6c6962636f72652e6a6176612e696f2e53657269616c697a6174696f6" + "e54657374245761734f626a656374000000000000000002000149000169787000000000"; - wasObjectInitializedFlag = false; + assertFalse(wasObjectInitializedFlag); try { SerializationTester.deserializeHex(s); fail(); diff --git a/luni/src/test/java/libcore/java/lang/ArrayIndexOutOfBoundsExceptionTest.java b/luni/src/test/java/libcore/java/lang/ArrayIndexOutOfBoundsExceptionTest.java deleted file mode 100644 index 98e497d..0000000 --- a/luni/src/test/java/libcore/java/lang/ArrayIndexOutOfBoundsExceptionTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2010 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.lang; - -import junit.framework.TestCase; - -public final class ArrayIndexOutOfBoundsExceptionTest extends TestCase { - public void testAput() throws Exception { - byte[] bs = new byte[1]; - try { - bs[2] = 0; - fail(); - } catch (ArrayIndexOutOfBoundsException ex) { - assertEquals("length=1; index=2", ex.getMessage()); - } - } - - public void testAget() throws Exception { - byte[] bs = new byte[1]; - try { - byte b = bs[2]; - fail(); - } catch (ArrayIndexOutOfBoundsException ex) { - assertEquals("length=1; index=2", ex.getMessage()); - } - } - - public void testAputWide() throws Exception { - double[] ds = new double[1]; - try { - ds[2] = 0.0; - fail(); - } catch (ArrayIndexOutOfBoundsException ex) { - assertEquals("length=1; index=2", ex.getMessage()); - } - } - - public void testAgetWide() throws Exception { - double[] ds = new double[1]; - try { - double d = ds[2]; - fail(); - } catch (ArrayIndexOutOfBoundsException ex) { - assertEquals("length=1; index=2", ex.getMessage()); - } - } - - public void testAputObject() throws Exception { - Object[] os = new Object[1]; - try { - os[2] = null; - fail(); - } catch (ArrayIndexOutOfBoundsException ex) { - assertEquals("length=1; index=2", ex.getMessage()); - } - } - - public void testAgetObject() throws Exception { - Object[] os = new Object[1]; - try { - Object o = os[2]; - fail(); - } catch (ArrayIndexOutOfBoundsException ex) { - assertEquals("length=1; index=2", ex.getMessage()); - } - } -} diff --git a/luni/src/test/java/libcore/java/lang/ArrayStoreExceptionTest.java b/luni/src/test/java/libcore/java/lang/ArrayStoreExceptionTest.java deleted file mode 100644 index c25245f..0000000 --- a/luni/src/test/java/libcore/java/lang/ArrayStoreExceptionTest.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (C) 2010 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.lang; - -import junit.framework.TestCase; - -public final class ArrayStoreExceptionTest extends TestCase { - public void testArrayStoreException_store1() throws Exception { - Object[] array = new String[10]; - Object o = new Exception(); - try { - array[0] = o; - fail(); - } catch (ArrayStoreException ex) { - ex.printStackTrace(); - assertEquals("java.lang.Exception cannot be stored in an array of type " - + "java.lang.String[]", - ex.getMessage()); - } - } - - public void testArrayStoreException_store2() throws Exception { - Object[] array = new Nonce[10][]; - Object o = new Integer(5); - try { - array[0] = o; - fail(); - } catch (ArrayStoreException ex) { - assertEquals("java.lang.Integer cannot be stored in an array of type " - + "libcore.java.lang.ArrayStoreExceptionTest$Nonce[][]", - ex.getMessage()); - } - } - - public void testArrayStoreException_store3() throws Exception { - Object[] array = new Float[10][]; - Object o = new Nonce[1]; - try { - array[0] = o; - fail(); - } catch (ArrayStoreException ex) { - assertEquals("libcore.java.lang.ArrayStoreExceptionTest$Nonce[] cannot be stored " - + "in an array of type java.lang.Float[][]", - ex.getMessage()); - } - } - - public void testArrayStoreException_arraycopy1() throws Exception { - String[] src = new String[] { null, null, null, null, "hello", "goodbye" }; - Integer[] dest = new Integer[10]; - try { - System.arraycopy(src, 1, dest, 0, 5); - } catch (ArrayStoreException ex) { - ex.printStackTrace(); - assertEquals("source[4] of type java.lang.String cannot be stored in destination " - + "array of type java.lang.Integer[]", - ex.getMessage()); - } - } - - public void testArrayStoreException_arraycopy2() throws Exception { - String[] src = new String[1]; - int[] dest = new int[1]; - try { - System.arraycopy(src, 0, dest, 0, 1); - } catch (ArrayStoreException ex) { - assertEquals("java.lang.String[] and int[] are incompatible array types", - ex.getMessage()); - } - } - - public void testArrayStoreException_arraycopy3() throws Exception { - float[] src = new float[1]; - Runnable[] dest = new Runnable[1]; - try { - System.arraycopy(src, 0, dest, 0, 1); - } catch (ArrayStoreException ex) { - assertEquals("float[] and java.lang.Runnable[] are incompatible array types", - ex.getMessage()); - } - } - - public void testArrayStoreException_arraycopy4() throws Exception { - boolean[] src = new boolean[1]; - double[][] dest = new double[1][]; - try { - System.arraycopy(src, 0, dest, 0, 1); - } catch (ArrayStoreException ex) { - assertEquals("boolean[] and double[][] are incompatible array types", - ex.getMessage()); - } - } - - public void testArrayStoreException_arraycopy5() throws Exception { - String src = "blort"; - Object[] dest = new Object[1]; - try { - System.arraycopy(src, 0, dest, 0, 1); - } catch (ArrayStoreException ex) { - assertEquals("source of type java.lang.String is not an array", - ex.getMessage()); - } - } - - public void testArrayStoreException_arraycopy6() throws Exception { - Object[] src = new Object[1]; - Integer dest = new Integer(5); - try { - System.arraycopy(src, 0, dest, 0, 1); - } catch (ArrayStoreException ex) { - assertEquals("destination of type java.lang.Integer is not an array", - ex.getMessage()); - } - } - - public void testArrayStoreException_arraycopy7() throws Exception { - /* - * This test demonstrates that the exception message complains - * about the source in cases where neither source nor - * destination is an array. - */ - Nonce src = new Nonce(); - String dest = "blort"; - try { - System.arraycopy(src, 0, dest, 0, 1); - } catch (ArrayStoreException ex) { - assertEquals("source of type libcore.java.lang.ArrayStoreExceptionTest$Nonce " - + "is not an array", - ex.getMessage()); - } - } - - /** - * This class is just used so that we have an example of getting a - * message that includes an inner class. - */ - private static class Nonce { - // This space intentionally left blank. - } -} diff --git a/luni/src/test/java/libcore/java/lang/CharacterTest.java b/luni/src/test/java/libcore/java/lang/CharacterTest.java index 48284d6..8c6f06f 100644 --- a/luni/src/test/java/libcore/java/lang/CharacterTest.java +++ b/luni/src/test/java/libcore/java/lang/CharacterTest.java @@ -242,7 +242,14 @@ public class CharacterTest extends junit.framework.TestCase { Method m = Character.class.getDeclaredMethod("isSpaceChar" + "Impl", int.class); m.setAccessible(true); for (int i = 0; i <= 0xffff; ++i) { - if((Boolean) m.invoke(null, i) != Character.isSpaceChar(i)) System.out.println(i); + // ICU and the RI disagree about character 0x180e. Remove this special case if this changes + // or Android decides to follow ICU exactly. + if (i == 0x180e) { + assertTrue(Character.isSpaceChar(i)); + assertFalse((Boolean) m.invoke(null, i)); + } else { + assertEquals("Failed for character " + i, m.invoke(null, i), Character.isSpaceChar(i)); + } } } @@ -260,7 +267,26 @@ public class CharacterTest extends junit.framework.TestCase { Method m = Character.class.getDeclaredMethod("isWhitespace" + "Impl", int.class); m.setAccessible(true); for (int i = 0; i <= 0xffff; ++i) { - assertEquals(m.invoke(null, i), Character.isWhitespace(i)); + // ICU and the RI disagree about character 0x180e. Remove this special case if this changes + // or Android decides to follow ICU exactly. + if (i == 0x180e) { + assertTrue(Character.isWhitespace(i)); + assertFalse((Boolean) m.invoke(null, i)); + } else { + assertEquals("Failed for character " + i, m.invoke(null, i), Character.isWhitespace(i)); + } } } + + // http://b/15492712 + public void test_getDirectionality() throws Exception { + // We shouldn't throw an exception for any code point. + for (int c = '\u0000'; c <= Character.MAX_VALUE; ++c) { + Character.getDirectionality(c); + } + assertEquals(Character.DIRECTIONALITY_UNDEFINED, Character.getDirectionality(0x2066)); + assertEquals(Character.DIRECTIONALITY_UNDEFINED, Character.getDirectionality(0x2067)); + assertEquals(Character.DIRECTIONALITY_UNDEFINED, Character.getDirectionality(0x2068)); + assertEquals(Character.DIRECTIONALITY_UNDEFINED, Character.getDirectionality(0x2069)); + } } diff --git a/luni/src/test/java/libcore/java/lang/ClassCastExceptionTest.java b/luni/src/test/java/libcore/java/lang/ClassCastExceptionTest.java index ec3aa46..3c10aa8 100644 --- a/luni/src/test/java/libcore/java/lang/ClassCastExceptionTest.java +++ b/luni/src/test/java/libcore/java/lang/ClassCastExceptionTest.java @@ -23,16 +23,6 @@ import java.util.EnumSet; import junit.framework.TestCase; public final class ClassCastExceptionTest extends TestCase { - public void testCast() throws Exception { - Object o = new Exception(); - try { - String s = (String) o; - fail(); - } catch (ClassCastException ex) { - assertEquals("java.lang.Exception cannot be cast to java.lang.String", ex.getMessage()); - } - } - public void testClassCast() throws Exception { Object o = new Exception(); try { @@ -53,69 +43,6 @@ public final class ClassCastExceptionTest extends TestCase { } } - public void testCastOperator() throws Exception { - try { - Object o = (InputStream) makeInteger(); - fail(); - } catch (ClassCastException ex) { - assertEquals("java.lang.Integer cannot be cast to java.io.InputStream", - ex.getMessage()); - } - } - - public void testCastOperatorWithArrays() throws Exception { - try { - Object o = (E) makeArray(String.class); - fail(); - } catch (ClassCastException ex) { - assertEquals("java.lang.String[] cannot be cast to " - + "libcore.java.lang.ClassCastExceptionTest$E", - ex.getMessage()); - } - - try { - Object o = (E) makeArray(float.class); - fail(); - } catch (ClassCastException ex) { - assertEquals("float[] cannot be cast to libcore.java.lang.ClassCastExceptionTest$E", - ex.getMessage()); - } - - try { - Object o = (E) makeArray(char[].class); - fail(); - } catch (ClassCastException ex) { - assertEquals("char[][] cannot be cast to libcore.java.lang.ClassCastExceptionTest$E", - ex.getMessage()); - } - - try { - Object o = (Object[][][]) makeInteger(); - fail(); - } catch (ClassCastException ex) { - assertEquals("java.lang.Integer cannot be cast to java.lang.Object[][][]", - ex.getMessage()); - } - } - - /** - * Helper for {@link #testCastOperator} and {@link - * #testCastOperatorWithArrays}, above. It's important that the - * return type is {@code Object}, since otherwise the compiler - * will just reject the code. - */ - private static Object makeInteger() { - return new Integer(5); - } - - /** - * Helper for {@link #testCastOperatorWithArrays} above. It's important that - * the return type is {@code Object}. - */ - private static Object makeArray(Class clazz) { - return Array.newInstance(clazz, 1); - } - enum E { A, B, C }; enum F { A, B, C }; @@ -125,7 +52,6 @@ public final class ClassCastExceptionTest extends TestCase { m.put(F.A, "world"); fail(); } catch (ClassCastException ex) { - ex.printStackTrace(); assertNotNull(ex.getMessage()); } } @@ -136,7 +62,6 @@ public final class ClassCastExceptionTest extends TestCase { m.add(F.A); fail(); } catch (ClassCastException ex) { - ex.printStackTrace(); assertNotNull(ex.getMessage()); } } @@ -148,7 +73,6 @@ public final class ClassCastExceptionTest extends TestCase { m.addAll(n); fail(); } catch (ClassCastException ex) { - ex.printStackTrace(); assertNotNull(ex.getMessage()); } } @@ -170,7 +94,6 @@ public final class ClassCastExceptionTest extends TestCase { m.add(HugeF.A0); fail(); } catch (ClassCastException ex) { - ex.printStackTrace(); assertNotNull(ex.getMessage()); } } @@ -182,7 +105,6 @@ public final class ClassCastExceptionTest extends TestCase { m.addAll(n); fail(); } catch (ClassCastException ex) { - ex.printStackTrace(); assertNotNull(ex.getMessage()); } } diff --git a/luni/src/test/java/libcore/java/lang/ClassNotFoundExceptionTest.java b/luni/src/test/java/libcore/java/lang/ClassNotFoundExceptionTest.java deleted file mode 100644 index 6eb97c2..0000000 --- a/luni/src/test/java/libcore/java/lang/ClassNotFoundExceptionTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2011 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.lang; - -import junit.framework.TestCase; - -public final class ClassNotFoundExceptionTest extends TestCase { - public void testIllegalName() throws Exception { - try { - // There is no such thing as an array of void. - Class.forName("[V"); - fail(); - } catch (ClassNotFoundException ex) { - assertEquals("[V", ex.getMessage()); - } - } - - public void testValidName() throws Exception { - try { - Class.forName("blort.Zorch"); - fail(); - } catch (ClassNotFoundException ex) { - assertEquals("blort.Zorch", ex.getMessage()); - } - } - - public void testValidArrayName() throws Exception { - try { - Class.forName("[[Lblort.Zorch;"); - fail(); - } catch (ClassNotFoundException ex) { - assertEquals("[[Lblort.Zorch;", ex.getMessage()); - } - } -} diff --git a/luni/src/test/java/libcore/java/lang/ClassTest.java b/luni/src/test/java/libcore/java/lang/ClassTest.java new file mode 100644 index 0000000..15298ea --- /dev/null +++ b/luni/src/test/java/libcore/java/lang/ClassTest.java @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2013 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.lang; + +import junit.framework.TestCase; + +public class ClassTest extends TestCase { + + interface Foo { + public void foo(); + } + + interface ParameterizedFoo<T> { + public void foo(T param); + } + + interface ParameterizedBar<T> extends ParameterizedFoo<T> { + public void bar(T param); + } + + interface ParameterizedBaz extends ParameterizedFoo<String> { + + } + + public void test_getGenericSuperclass_nullReturnCases() { + // Should always return null for interfaces. + assertNull(Foo.class.getGenericSuperclass()); + assertNull(ParameterizedFoo.class.getGenericSuperclass()); + assertNull(ParameterizedBar.class.getGenericSuperclass()); + assertNull(ParameterizedBaz.class.getGenericSuperclass()); + + assertNull(Object.class.getGenericSuperclass()); + assertNull(void.class.getGenericSuperclass()); + assertNull(int.class.getGenericSuperclass()); + } + + public void test_getGenericSuperclass_returnsObjectForArrays() { + assertSame(Object.class, (new Integer[0]).getClass().getGenericSuperclass()); + } +} diff --git a/luni/src/test/java/libcore/java/lang/DoubleTest.java b/luni/src/test/java/libcore/java/lang/DoubleTest.java index 687d3e3..85281ba 100644 --- a/luni/src/test/java/libcore/java/lang/DoubleTest.java +++ b/luni/src/test/java/libcore/java/lang/DoubleTest.java @@ -127,4 +127,19 @@ public class DoubleTest extends TestCase { assertEquals(2.2250738585072014E-308, Double.parseDouble("2.22507385850720129978001e-308")); assertEquals(-2.2250738585072014E-308, Double.parseDouble("-2.2250738585072012e-308")); } + + // https://code.google.com/p/android/issues/detail?id=71216 + public void testParse_bug71216() { + try { + Double.parseDouble("73706943-9580-4406-a02f-0304e4324844"); + fail(); + } catch (NumberFormatException expected) { + } + + try { + Double.parseDouble("bade999999999999999999999999999999"); + fail(); + } catch (NumberFormatException expected) { + } + } } diff --git a/luni/src/test/java/libcore/java/lang/IntegerTest.java b/luni/src/test/java/libcore/java/lang/IntegerTest.java index 2d8c082..b54b322 100644 --- a/luni/src/test/java/libcore/java/lang/IntegerTest.java +++ b/luni/src/test/java/libcore/java/lang/IntegerTest.java @@ -16,19 +16,118 @@ package libcore.java.lang; +import java.util.Properties; + public class IntegerTest extends junit.framework.TestCase { - public void test_compare() throws Exception { - final int min = Integer.MIN_VALUE; - final int zero = 0; - final int max = Integer.MAX_VALUE; - assertTrue(Integer.compare(max, max) == 0); - assertTrue(Integer.compare(min, min) == 0); - assertTrue(Integer.compare(zero, zero) == 0); - assertTrue(Integer.compare(max, zero) > 0); - assertTrue(Integer.compare(max, min) > 0); - assertTrue(Integer.compare(zero, max) < 0); - assertTrue(Integer.compare(zero, min) > 0); - assertTrue(Integer.compare(min, zero) < 0); - assertTrue(Integer.compare(min, max) < 0); + + public void testSystemProperties() { + Properties originalProperties = System.getProperties(); + try { + Properties testProperties = new Properties(); + testProperties.put("testIncInt", "notInt"); + System.setProperties(testProperties); + assertNull("returned incorrect default Integer", + Integer.getInteger("testIncInt")); + assertEquals(new Integer(4), Integer.getInteger("testIncInt", 4)); + assertEquals(new Integer(4), + Integer.getInteger("testIncInt", new Integer(4))); + } finally { + System.setProperties(originalProperties); } + } + + public void testCompare() throws Exception { + final int min = Integer.MIN_VALUE; + final int zero = 0; + final int max = Integer.MAX_VALUE; + assertTrue(Integer.compare(max, max) == 0); + assertTrue(Integer.compare(min, min) == 0); + assertTrue(Integer.compare(zero, zero) == 0); + assertTrue(Integer.compare(max, zero) > 0); + assertTrue(Integer.compare(max, min) > 0); + assertTrue(Integer.compare(zero, max) < 0); + assertTrue(Integer.compare(zero, min) > 0); + assertTrue(Integer.compare(min, zero) < 0); + assertTrue(Integer.compare(min, max) < 0); + } + + public void testParseInt() throws Exception { + assertEquals(0, Integer.parseInt("+0", 10)); + assertEquals(473, Integer.parseInt("+473", 10)); + assertEquals(255, Integer.parseInt("+FF", 16)); + assertEquals(102, Integer.parseInt("+1100110", 2)); + assertEquals(2147483647, Integer.parseInt("+2147483647", 10)); + assertEquals(411787, Integer.parseInt("Kona", 27)); + assertEquals(411787, Integer.parseInt("+Kona", 27)); + assertEquals(-145, Integer.parseInt("-145", 10)); + + try { + Integer.parseInt("--1", 10); // multiple sign chars + fail(); + } catch (NumberFormatException expected) {} + + try { + Integer.parseInt("++1", 10); // multiple sign chars + fail(); + } catch (NumberFormatException expected) {} + + try { + Integer.parseInt("Kona", 10); // base too small + fail(); + } catch (NumberFormatException expected) {} + } + + public void testDecodeInt() throws Exception { + assertEquals(0, Integer.decode("+0").intValue()); + assertEquals(473, Integer.decode("+473").intValue()); + assertEquals(255, Integer.decode("+0xFF").intValue()); + assertEquals(16, Integer.decode("+020").intValue()); + assertEquals(2147483647, Integer.decode("+2147483647").intValue()); + assertEquals(-73, Integer.decode("-73").intValue()); + assertEquals(-255, Integer.decode("-0xFF").intValue()); + assertEquals(255, Integer.decode("+#FF").intValue()); + assertEquals(-255, Integer.decode("-#FF").intValue()); + + try { + Integer.decode("--1"); // multiple sign chars + fail(); + } catch (NumberFormatException expected) {} + + try { + Integer.decode("++1"); // multiple sign chars + fail(); + } catch (NumberFormatException expected) {} + + try { + Integer.decode("-+1"); // multiple sign chars + fail(); + } catch (NumberFormatException expected) {} + + try { + Integer.decode("Kona"); // invalid number + fail(); + } catch (NumberFormatException expected) {} + } + + public void testParsePositiveInt() throws Exception { + assertEquals(0, Integer.parsePositiveInt("0", 10)); + assertEquals(473, Integer.parsePositiveInt("473", 10)); + assertEquals(255, Integer.parsePositiveInt("FF", 16)); + + try { + Integer.parsePositiveInt("-1", 10); + fail(); + } catch (NumberFormatException e) {} + + try { + Integer.parsePositiveInt("+1", 10); + fail(); + } catch (NumberFormatException e) {} + + try { + Integer.parsePositiveInt("+0", 16); + fail(); + } catch (NumberFormatException e) {} + } + } diff --git a/luni/src/test/java/libcore/java/lang/LongTest.java b/luni/src/test/java/libcore/java/lang/LongTest.java index 9e143da..0d1741a 100644 --- a/luni/src/test/java/libcore/java/lang/LongTest.java +++ b/luni/src/test/java/libcore/java/lang/LongTest.java @@ -16,8 +16,25 @@ package libcore.java.lang; +import java.util.Properties; + public class LongTest extends junit.framework.TestCase { - public void test_compare() throws Exception { + + public void testSystemProperties() { + Properties originalProperties = System.getProperties(); + try { + Properties testProperties = new Properties(); + testProperties.put("testIncLong", "string"); + System.setProperties(testProperties); + assertNull(Long.getLong("testIncLong")); + assertEquals(new Long(4), Long.getLong("testIncLong", 4L)); + assertEquals(new Long(4), Long.getLong("testIncLong", new Long(4))); + } finally { + System.setProperties(originalProperties); + } + } + + public void testCompare() throws Exception { final long min = Long.MIN_VALUE; final long zero = 0L; final long max = Long.MAX_VALUE; @@ -32,11 +49,91 @@ public class LongTest extends junit.framework.TestCase { assertTrue(Long.compare(min, max) < 0); } - public void test_signum() throws Exception { + public void testSignum() throws Exception { assertEquals(0, Long.signum(0)); assertEquals(1, Long.signum(1)); assertEquals(-1, Long.signum(-1)); assertEquals(1, Long.signum(Long.MAX_VALUE)); assertEquals(-1, Long.signum(Long.MIN_VALUE)); } + + public void testParsePositiveLong() throws Exception { + assertEquals(0, Long.parsePositiveLong("0", 10)); + assertEquals(473, Long.parsePositiveLong("473", 10)); + assertEquals(255, Long.parsePositiveLong("FF", 16)); + + try { + Long.parsePositiveLong("-1", 10); + fail(); + } catch (NumberFormatException e) {} + + try { + Long.parsePositiveLong("+1", 10); + fail(); + } catch (NumberFormatException e) {} + + try { + Long.parsePositiveLong("+0", 16); + fail(); + } catch (NumberFormatException e) {} + } + + public void testParseLong() throws Exception { + assertEquals(0, Long.parseLong("+0", 10)); + assertEquals(473, Long.parseLong("+473", 10)); + assertEquals(255, Long.parseLong("+FF", 16)); + assertEquals(102, Long.parseLong("+1100110", 2)); + assertEquals(Long.MAX_VALUE, Long.parseLong("+" + Long.MAX_VALUE, 10)); + assertEquals(411787, Long.parseLong("Kona", 27)); + assertEquals(411787, Long.parseLong("+Kona", 27)); + assertEquals(-145, Long.parseLong("-145", 10)); + + try { + Long.parseLong("--1", 10); // multiple sign chars + fail(); + } catch (NumberFormatException expected) {} + + try { + Long.parseLong("++1", 10); // multiple sign chars + fail(); + } catch (NumberFormatException expected) {} + + try { + Long.parseLong("Kona", 10); // base to small + fail(); + } catch (NumberFormatException expected) {} + } + + public void testDecodeLong() throws Exception { + assertEquals(0, Long.decode("+0").longValue()); + assertEquals(473, Long.decode("+473").longValue()); + assertEquals(255, Long.decode("+0xFF").longValue()); + assertEquals(16, Long.decode("+020").longValue()); + assertEquals(Long.MAX_VALUE, Long.decode("+" + Long.MAX_VALUE).longValue()); + assertEquals(-73, Long.decode("-73").longValue()); + assertEquals(-255, Long.decode("-0xFF").longValue()); + assertEquals(255, Long.decode("+#FF").longValue()); + assertEquals(-255, Long.decode("-#FF").longValue()); + + try { + Long.decode("--1"); // multiple sign chars + fail(); + } catch (NumberFormatException expected) {} + + try { + Long.decode("++1"); // multiple sign chars + fail(); + } catch (NumberFormatException expected) {} + + try { + Long.decode("+-1"); // multiple sign chars + fail(); + } catch (NumberFormatException expected) {} + + try { + Long.decode("Kona"); // invalid number + fail(); + } catch (NumberFormatException expected) {} + } + } diff --git a/luni/src/test/java/libcore/java/lang/OldAndroidParseIntTest.java b/luni/src/test/java/libcore/java/lang/OldAndroidParseIntTest.java deleted file mode 100644 index 08351d6..0000000 --- a/luni/src/test/java/libcore/java/lang/OldAndroidParseIntTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (C) 2008 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.lang; - -import junit.framework.TestCase; - -/** - * Tests for functionality of class Integer to parse integers. - */ -public class OldAndroidParseIntTest extends TestCase { - - public void testParseInt() throws Exception { - assertEquals(0, Integer.parseInt("0", 10)); - assertEquals(473, Integer.parseInt("473", 10)); - assertEquals(0, Integer.parseInt("-0", 10)); - assertEquals(-255, Integer.parseInt("-FF", 16)); - assertEquals(102, Integer.parseInt("1100110", 2)); - assertEquals(2147483647, Integer.parseInt("2147483647", 10)); - assertEquals(-2147483648, Integer.parseInt("-2147483648", 10)); - - try { - Integer.parseInt("2147483648", 10); - fail(); - } catch (NumberFormatException e) { - // ok - } - - try { - Integer.parseInt("-2147483649", 10); - fail(); - } catch (NumberFormatException e) { - // ok - } - - // One digit too many - try { - Integer.parseInt("21474836470", 10); - fail(); - } catch (NumberFormatException e) { - // ok - } - - try { - Integer.parseInt("-21474836480", 10); - fail(); - } catch (NumberFormatException e) { - // ok - } - - try { - Integer.parseInt("21474836471", 10); - fail(); - } catch (NumberFormatException e) { - // ok - } - - try { - Integer.parseInt("-21474836481", 10); - fail(); - } catch (NumberFormatException e) { - // ok - } - - try { - Integer.parseInt("214748364710", 10); - fail(); - } catch (NumberFormatException e) { - // ok - } - - try { - Integer.parseInt("-214748364811", 10); - fail(); - } catch (NumberFormatException e) { - // ok - } - - try { - Integer.parseInt("99", 8); - fail(); - } catch (NumberFormatException e) { - // ok - } - - try { - Integer.parseInt("Kona", 10); - fail(); - } catch (NumberFormatException e) { - // ok - } - - assertEquals(411787, Integer.parseInt("Kona", 27)); - } -} diff --git a/luni/src/test/java/libcore/java/lang/OldClassTest.java b/luni/src/test/java/libcore/java/lang/OldClassTest.java index 0f7ce42..23a42bd 100644 --- a/luni/src/test/java/libcore/java/lang/OldClassTest.java +++ b/luni/src/test/java/libcore/java/lang/OldClassTest.java @@ -720,8 +720,20 @@ public class OldClassTest extends junit.framework.TestCase { } public void test_getDeclaringClass() { - assertNull(OldClassTest.class.getDeclaringClass()); - assertNotNull(PublicTestClass.class.getDeclaringClass()); + assertEquals(OldClassTest.class, Intf1.class.getDeclaringClass()); + assertEquals(null, Serializable.class.getDeclaringClass()); + assertEquals(null, OldClassTest.class.getDeclaringClass()); + + assertEquals(OldClassTest.class, PublicTestClass.class.getDeclaringClass()); + + // https://code.google.com/p/android/issues/detail?id=61003 + assertEquals(null, new Object() {}.getClass().getDeclaringClass()); + assertEquals(null, new AnonymousMemberFixture().instanceOfAnonymousClass.getClass().getDeclaringClass()); + + // Arrays, primitive types, and void all return null. + assertEquals(null, char[].class.getDeclaringClass()); + assertEquals(null, int.class.getDeclaringClass()); + assertEquals(null, void.class.getDeclaringClass()); } public void test_getFieldLjava_lang_String() throws Exception { @@ -1022,3 +1034,7 @@ public class OldClassTest extends junit.framework.TestCase { assertNull(clazz.getResourceAsStream("libcore/java/lang/HelloWorld.txt")); } } + +class AnonymousMemberFixture { + Object instanceOfAnonymousClass = new Object() {}; +} diff --git a/luni/src/test/java/libcore/java/lang/OldIntegerTest.java b/luni/src/test/java/libcore/java/lang/OldIntegerTest.java deleted file mode 100644 index 462ee19..0000000 --- a/luni/src/test/java/libcore/java/lang/OldIntegerTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.lang; - -import java.util.Properties; -import junit.framework.TestCase; - -public class OldIntegerTest extends TestCase { - private Properties orgProps; - - @Override - protected void setUp() { - orgProps = System.getProperties(); - } - - @Override - protected void tearDown() { - System.setProperties(orgProps); - } - - public void test_getIntegerLjava_lang_StringI() { - // Test for method java.lang.Integer - // java.lang.Integer.getInteger(java.lang.String, int) - Properties tProps = new Properties(); - tProps.put("testIncInt", "notInt"); - System.setProperties(tProps); - assertTrue("returned incorrect default Integer", Integer.getInteger( - "testIncInt", 4).equals(new Integer(4))); - } - - public void test_getIntegerLjava_lang_StringLjava_lang_Integer() { - // Test for method java.lang.Integer - // java.lang.Integer.getInteger(java.lang.String, java.lang.Integer) - Properties tProps = new Properties(); - tProps.put("testIncInt", "notInt"); - System.setProperties(tProps); - assertTrue("returned incorrect default Integer", Integer.getInteger( - "testIncInt", new Integer(4)).equals(new Integer(4))); - } - - public void test_intValue() { - assertEquals(Integer.MAX_VALUE, new Integer(Integer.MAX_VALUE).intValue()); - assertEquals(Integer.MIN_VALUE, new Integer(Integer.MIN_VALUE).intValue()); - } - - public void test_longValue() { - assertEquals(Integer.MAX_VALUE, new Integer(Integer.MAX_VALUE).longValue()); - assertEquals(Integer.MIN_VALUE, new Integer(Integer.MIN_VALUE).longValue()); - } - - public void test_shortValue() { - assertEquals(-1, new Integer(Integer.MAX_VALUE).shortValue()); - assertEquals(0, new Integer(Integer.MIN_VALUE).shortValue()); - } -} diff --git a/luni/src/test/java/libcore/java/lang/OldLongTest.java b/luni/src/test/java/libcore/java/lang/OldLongTest.java deleted file mode 100644 index 6fb7d49..0000000 --- a/luni/src/test/java/libcore/java/lang/OldLongTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.lang; - -import java.util.Properties; -import junit.framework.TestCase; - -public class OldLongTest extends TestCase { - private Properties orgProps; - - @Override - protected void setUp() { - orgProps = System.getProperties(); - } - - @Override - protected void tearDown() { - System.setProperties(orgProps); - } - - public void test_getLongLjava_lang_String() { - Properties tProps = new Properties(); - tProps.put("testLong", "99"); - tProps.put("testIncLong", "string"); - System.setProperties(tProps); - assertNull("returned incorrect default Long", - Long.getLong("testIncLong")); - } - - public void test_getLongLjava_lang_StringJ() { - // Test for method java.lang.Long - // java.lang.Long.getLong(java.lang.String, long) - Properties tProps = new Properties(); - tProps.put("testIncLong", "string"); - System.setProperties(tProps); - assertTrue("returned incorrect default Long", Long.getLong("testIncLong", 4L) - .equals(new Long(4))); - } - - public void test_getLongLjava_lang_StringLjava_lang_Long() { - // Test for method java.lang.Long - // java.lang.Long.getLong(java.lang.String, java.lang.Long) - Properties tProps = new Properties(); - tProps.put("testIncLong", "string"); - System.setProperties(tProps); - assertTrue("returned incorrect default Long", Long.getLong("testIncLong", - new Long(4)).equals(new Long(4))); - } - - public void test_floatValue() { - assertEquals(Long.MAX_VALUE, new Long(Long.MAX_VALUE).floatValue(), 0F); - assertEquals(Long.MIN_VALUE, new Long(Long.MIN_VALUE).floatValue(), 0F); - } - - public void test_intValue() { - assertEquals(-1, new Long(Long.MAX_VALUE).intValue()); - assertEquals(0, new Long(Long.MIN_VALUE).intValue()); - } - - public void test_longValue() { - assertEquals(Long.MAX_VALUE, new Long(Long.MAX_VALUE).longValue()); - assertEquals(Long.MIN_VALUE, new Long(Long.MIN_VALUE).longValue()); - } - - public void test_shortValue() { - assertEquals(-1, new Long(Long.MAX_VALUE).shortValue()); - assertEquals(0, new Long(Long.MIN_VALUE).shortValue()); - } -} diff --git a/luni/src/test/java/libcore/java/lang/OldObjectTest.java b/luni/src/test/java/libcore/java/lang/OldObjectTest.java index 3ab0327..f7a3781 100644 --- a/luni/src/test/java/libcore/java/lang/OldObjectTest.java +++ b/luni/src/test/java/libcore/java/lang/OldObjectTest.java @@ -36,6 +36,16 @@ public class OldObjectTest extends TestCase { TestThread1 thr1; TestThread2 thr2; + public void test_hashCode() { + Object o1 = new Object(); + Object o2 = new Object(); + int h1 = System.identityHashCode(o1); + int h2 = System.identityHashCode(o2); + assertEquals(h1, o1.hashCode()); + assertEquals(h2, o2.hashCode()); + assertTrue(h1 != h2); + } + public void test_clone() { MockCloneableObject mco = new MockCloneableObject(); try { diff --git a/luni/src/test/java/libcore/java/lang/OldRuntimeTest.java b/luni/src/test/java/libcore/java/lang/OldRuntimeTest.java index 0926569..294cea2 100644 --- a/luni/src/test/java/libcore/java/lang/OldRuntimeTest.java +++ b/luni/src/test/java/libcore/java/lang/OldRuntimeTest.java @@ -34,28 +34,6 @@ public class OldRuntimeTest extends junit.framework.TestCase { InputStream is; - public void test_freeMemory() { - // Heap might grow or do GC at any time, - // so we can't really test a lot. Hence - // we are just doing some basic sanity - // checks here. - assertTrue("must have some free memory", - r.freeMemory() > 0); - - assertTrue("must not exceed total memory", - r.freeMemory() < r.totalMemory()); - - long before = r.totalMemory() - r.freeMemory(); - Vector<byte[]> v = new Vector<byte[]>(); - for (int i = 1; i < 10; i++) { - v.addElement(new byte[10000]); - } - long after = r.totalMemory() - r.freeMemory(); - - assertTrue("free memory must change with allocations", - after != before); - } - public void test_getRuntime() { // Test for method java.lang.Runtime java.lang.Runtime.getRuntime() assertNotNull(Runtime.getRuntime()); @@ -451,10 +429,6 @@ public class OldRuntimeTest extends junit.framework.TestCase { } } - public void test_maxMemory() { - assertTrue(Runtime.getRuntime().maxMemory() < Long.MAX_VALUE); - } - public void test_traceInstructions() { Runtime.getRuntime().traceInstructions(false); Runtime.getRuntime().traceInstructions(true); diff --git a/luni/src/test/java/libcore/java/lang/ProcessBuilderTest.java b/luni/src/test/java/libcore/java/lang/ProcessBuilderTest.java index d03ae65..9766cef 100644 --- a/luni/src/test/java/libcore/java/lang/ProcessBuilderTest.java +++ b/luni/src/test/java/libcore/java/lang/ProcessBuilderTest.java @@ -22,10 +22,10 @@ import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; -import libcore.dalvik.system.CloseGuardTester; +import libcore.java.util.AbstractResourceLeakageDetectorTestCase; import static tests.support.Support_Exec.execAndCheckOutput; -public class ProcessBuilderTest extends junit.framework.TestCase { +public class ProcessBuilderTest extends AbstractResourceLeakageDetectorTestCase { private static String shell() { String deviceSh = "/system/bin/sh"; @@ -84,14 +84,8 @@ public class ProcessBuilderTest extends junit.framework.TestCase { } public void testDestroyDoesNotLeak() throws IOException { - CloseGuardTester closeGuardTester = new CloseGuardTester(); - try { - Process process = new ProcessBuilder(shell(), "-c", "echo out; echo err 1>&2").start(); - process.destroy(); - closeGuardTester.assertEverythingWasClosed(); - } finally { - closeGuardTester.close(); - } + Process process = new ProcessBuilder(shell(), "-c", "echo out; echo err 1>&2").start(); + process.destroy(); } public void testEnvironmentMapForbidsNulls() throws Exception { diff --git a/luni/src/test/java/libcore/java/lang/StringBuilderTest.java b/luni/src/test/java/libcore/java/lang/StringBuilderTest.java new file mode 100644 index 0000000..1f9abbf --- /dev/null +++ b/luni/src/test/java/libcore/java/lang/StringBuilderTest.java @@ -0,0 +1,132 @@ +/* + * Copyright (C) 2011 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.lang; + +public class StringBuilderTest extends junit.framework.TestCase { + // See https://code.google.com/p/android/issues/detail?id=60639 + public void test_deleteChatAt_lastRange() { + StringBuilder sb = new StringBuilder("oarFish_"); + sb.append('a'); + String oarFishA = sb.toString(); + + sb.deleteCharAt(sb.length() - 1); + sb.append('b'); + String oarFishB = sb.toString(); + + assertEquals("oarFish_a", oarFishA); + assertEquals("oarFish_b", oarFishB); + } + + // See https://code.google.com/p/android/issues/detail?id=60639 + public void test_deleteCharAt_lastChar() { + StringBuilder sb = new StringBuilder(); + sb.append('a'); + String a = sb.toString(); + + sb.deleteCharAt(0); + sb.append('b'); + String b = sb.toString(); + + assertEquals("a", a); + assertEquals("b", b); + } + + // See https://code.google.com/p/android/issues/detail?id=60639 + public void test_delete_endsAtLastChar() { + StringBuilder sb = new StringBuilder("newGuineaSinging"); + sb.append("Dog"); + String dog = sb.toString(); + + sb.delete(sb.length() - 3, sb.length()); + sb.append("Cat"); + String cat = sb.toString(); + + // NOTE: It's important that these asserts stay at the end of this test. + // We're trying to make sure that replacing chars in the builder does not + // change strings that have already been returned from it. + assertEquals("newGuineaSingingDog", dog); + assertEquals("newGuineaSingingCat", cat); + } + + public void test_deleteCharAt_boundsChecks() { + StringBuilder sb = new StringBuilder("yeti"); + + try { + sb.deleteCharAt(sb.length()); + fail(); + } catch (StringIndexOutOfBoundsException expected) { + } + + try { + sb.deleteCharAt(-1); + fail(); + } catch (StringIndexOutOfBoundsException expected) { + } + } + + public void test_delete_boundsChecks() throws Exception { + StringBuilder sb = new StringBuilder("yeti"); + + // The cases below ahould not throw (even though they are clearly invalid + // ranges), because we promise not to throw if start == count as long as + // end >= start. + sb.delete(sb.length(), sb.length() + 2); + sb.delete(sb.length(), sb.length()); + + sb.delete(2, 2); + assertEquals("yeti", sb.toString()); + + // We must throw if start > count.... + try { + sb.delete(sb.length() + 2, sb.length() + 3); + fail(); + } catch (StringIndexOutOfBoundsException expected) { + } + + // ... even if the length of the range is 0. + try { + sb.delete(sb.length() + 2, sb.length() + 2); + fail(); + } catch (StringIndexOutOfBoundsException expected) { + } + + // Must throw if start < 0. + try { + sb.delete(-1, sb.length() -1); + fail(); + } catch (StringIndexOutOfBoundsException expected) { + } + + // A few commonly used specializations: sb.delete(0, 0) on an empty + // builder is a particularly common pattern. + StringBuilder sb2 = new StringBuilder(); + sb2.delete(0, sb2.length()); + sb2.delete(0, 12); + } + + // We shouldn't throw if the end index is > count, we should clamp it + // instead. + public void test_delete_clampsEnd() throws Exception { + StringBuilder sb = new StringBuilder("mogwai"); + + sb.delete(sb.length() - 1 , sb.length() + 2); + assertEquals("mogwa", sb.toString()); + + sb.delete(sb.length() - 1, sb.length()); + assertEquals("mogw", sb.toString()); + } +} diff --git a/luni/src/test/java/libcore/java/lang/StringIndexOutOfBoundsExceptionTest.java b/luni/src/test/java/libcore/java/lang/StringIndexOutOfBoundsExceptionTest.java deleted file mode 100644 index 822e37f..0000000 --- a/luni/src/test/java/libcore/java/lang/StringIndexOutOfBoundsExceptionTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2010 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.lang; - -import junit.framework.TestCase; - -public final class StringIndexOutOfBoundsExceptionTest extends TestCase { - public void testCharAt() throws Exception { - try { - "hello".charAt(-1); - fail(); - } catch (StringIndexOutOfBoundsException ex) { - assertEquals("length=5; index=-1", ex.getMessage()); - } - - try { - "hello".charAt(7); - fail(); - } catch (StringIndexOutOfBoundsException ex) { - assertEquals("length=5; index=7", ex.getMessage()); - } - } - - public void testSubstring() throws Exception { - try { - "hello there".substring(9,14); - fail(); - } catch (StringIndexOutOfBoundsException ex) { - assertEquals("length=11; regionStart=9; regionLength=5", - ex.getMessage()); - } - } -} diff --git a/luni/src/test/java/libcore/java/lang/StringTest.java b/luni/src/test/java/libcore/java/lang/StringTest.java index e16496b..bf162e5 100644 --- a/luni/src/test/java/libcore/java/lang/StringTest.java +++ b/luni/src/test/java/libcore/java/lang/StringTest.java @@ -174,7 +174,7 @@ public class StringTest extends TestCase { /** * Tests a widely assumed performance characteristic of String.substring(): - * that it reuses the original's backing array. Although behaviour should be + * that it reuses the original's backing array. Although behavior should be * correct even if this test fails, many applications may suffer * significant performance degradation. */ @@ -187,7 +187,7 @@ public class StringTest extends TestCase { /** * Tests a widely assumed performance characteristic of string's copy * constructor: that it ensures the backing array is the same length as the - * string. Although behaviour should be correct even if this test fails, + * string. Although behavior should be correct even if this test fails, * many applications may suffer significant performance degradation. */ public void testStringCopiesAvoidHeapRetention() throws IllegalAccessException { @@ -243,33 +243,43 @@ public class StringTest extends TestCase { }; public void testCaseMapping_tr_TR() { - Locale trTR = new Locale("tr", "TR"); - assertEquals(LATIN_SMALL_I, LATIN_SMALL_I.toLowerCase(trTR)); - assertEquals(LATIN_SMALL_I, LATIN_CAPITAL_I_WITH_DOT_ABOVE.toLowerCase(trTR)); - assertEquals(LATIN_SMALL_DOTLESS_I, LATIN_SMALL_DOTLESS_I.toLowerCase(trTR)); + Locale tr_TR = new Locale("tr", "TR"); + assertEquals(LATIN_SMALL_I, LATIN_SMALL_I.toLowerCase(tr_TR)); + assertEquals(LATIN_SMALL_I, LATIN_CAPITAL_I_WITH_DOT_ABOVE.toLowerCase(tr_TR)); + assertEquals(LATIN_SMALL_DOTLESS_I, LATIN_SMALL_DOTLESS_I.toLowerCase(tr_TR)); - assertEquals(LATIN_CAPITAL_I, LATIN_CAPITAL_I.toUpperCase(trTR)); - assertEquals(LATIN_CAPITAL_I_WITH_DOT_ABOVE, LATIN_CAPITAL_I_WITH_DOT_ABOVE.toUpperCase(trTR)); - assertEquals(LATIN_CAPITAL_I_WITH_DOT_ABOVE, LATIN_SMALL_I.toUpperCase(trTR)); + assertEquals(LATIN_CAPITAL_I, LATIN_CAPITAL_I.toUpperCase(tr_TR)); + assertEquals(LATIN_CAPITAL_I_WITH_DOT_ABOVE, LATIN_CAPITAL_I_WITH_DOT_ABOVE.toUpperCase(tr_TR)); + assertEquals(LATIN_CAPITAL_I_WITH_DOT_ABOVE, LATIN_SMALL_I.toUpperCase(tr_TR)); - assertEquals(LATIN_CAPITAL_I, LATIN_SMALL_DOTLESS_I.toUpperCase(trTR)); - assertEquals(LATIN_SMALL_DOTLESS_I, LATIN_CAPITAL_I.toLowerCase(trTR)); + assertEquals(LATIN_CAPITAL_I, LATIN_SMALL_DOTLESS_I.toUpperCase(tr_TR)); + assertEquals(LATIN_SMALL_DOTLESS_I, LATIN_CAPITAL_I.toLowerCase(tr_TR)); } public void testCaseMapping_en_US() { - Locale enUs = new Locale("en", "US"); - assertEquals(LATIN_CAPITAL_I, LATIN_SMALL_I.toUpperCase(enUs)); - assertEquals(LATIN_CAPITAL_I, LATIN_CAPITAL_I.toUpperCase(enUs)); - assertEquals(LATIN_CAPITAL_I_WITH_DOT_ABOVE, LATIN_CAPITAL_I_WITH_DOT_ABOVE.toUpperCase(enUs)); + Locale en_US = new Locale("en", "US"); + assertEquals(LATIN_CAPITAL_I, LATIN_SMALL_I.toUpperCase(en_US)); + assertEquals(LATIN_CAPITAL_I, LATIN_CAPITAL_I.toUpperCase(en_US)); + assertEquals(LATIN_CAPITAL_I_WITH_DOT_ABOVE, LATIN_CAPITAL_I_WITH_DOT_ABOVE.toUpperCase(en_US)); - assertEquals(LATIN_SMALL_I, LATIN_SMALL_I.toLowerCase(enUs)); - assertEquals(LATIN_SMALL_I, LATIN_CAPITAL_I.toLowerCase(enUs)); - assertEquals(LATIN_SMALL_DOTLESS_I, LATIN_SMALL_DOTLESS_I.toLowerCase(enUs)); + assertEquals(LATIN_SMALL_I, LATIN_SMALL_I.toLowerCase(en_US)); + assertEquals(LATIN_SMALL_I, LATIN_CAPITAL_I.toLowerCase(en_US)); + assertEquals(LATIN_SMALL_DOTLESS_I, LATIN_SMALL_DOTLESS_I.toLowerCase(en_US)); - assertEquals(LATIN_CAPITAL_I, LATIN_SMALL_DOTLESS_I.toUpperCase(enUs)); + assertEquals(LATIN_CAPITAL_I, LATIN_SMALL_DOTLESS_I.toUpperCase(en_US)); // http://b/3325799: the RI fails this because it's using an obsolete version of the Unicode rules. // Android correctly preserves canonical equivalence. (See the separate test for tr_TR.) - assertEquals(LATIN_SMALL_I + COMBINING_DOT_ABOVE, LATIN_CAPITAL_I_WITH_DOT_ABOVE.toLowerCase(enUs)); + assertEquals(LATIN_SMALL_I + COMBINING_DOT_ABOVE, LATIN_CAPITAL_I_WITH_DOT_ABOVE.toLowerCase(en_US)); + } + + public void testCaseMapping_el() { + Locale el_GR = new Locale("el", "GR"); + assertEquals("ΟΔΟΣ ΟΔΟΣ ΣΟ ΣΟ OΣ ΟΣ Σ ΕΞ", "ΟΔΌΣ Οδός Σο ΣΟ oΣ ΟΣ σ ἕξ".toUpperCase(el_GR)); + assertEquals("ΟΔΟΣ ΟΔΟΣ ΣΟ ΣΟ OΣ ΟΣ Σ ΕΞ", "ΟΔΌΣ Οδός Σο ΣΟ oΣ ΟΣ σ ἕξ".toUpperCase(el_GR)); + assertEquals("ΟΔΟΣ ΟΔΟΣ ΣΟ ΣΟ OΣ ΟΣ Σ ΕΞ", "ΟΔΌΣ Οδός Σο ΣΟ oΣ ΟΣ σ ἕξ".toUpperCase(el_GR)); + + Locale en_US = new Locale("en", "US"); + assertEquals("ΟΔΌΣ ΟΔΌΣ ΣΟ ΣΟ OΣ ΟΣ Σ ἝΞ", "ΟΔΌΣ Οδός Σο ΣΟ oΣ ΟΣ σ ἕξ".toUpperCase(en_US)); } public void testEqualsIgnoreCase_tr_TR() { @@ -349,12 +359,88 @@ public class StringTest extends TestCase { assertEquals("-*-w-*-o-*-r-*-l-*-d-*-", "hello world".substring(6).replace("", "-*-")); } - // http://b/11571917 public void test_String_getBytes() throws Exception { + // http://b/11571917 assertEquals("[-126, -96]", Arrays.toString("あ".getBytes("Shift_JIS"))); assertEquals("[-126, -87]", Arrays.toString("か".getBytes("Shift_JIS"))); assertEquals("[-105, 67]", Arrays.toString("佑".getBytes("Shift_JIS"))); assertEquals("[36]", Arrays.toString("$".getBytes("Shift_JIS"))); assertEquals("[-29, -127, -117]", Arrays.toString("か".getBytes("UTF-8"))); + + // http://b/11639117 + assertEquals("[-79, -72, -70, -48]", Arrays.toString("구분".getBytes("EUC-KR"))); + + + // https://code.google.com/p/android/issues/detail?id=63188 + assertEquals("[-77, -10, -64, -76, -63, -53]", Arrays.toString("出来了".getBytes("gbk"))); + assertEquals("[-77, -10, -64, -76]", Arrays.toString("出来".getBytes("gbk"))); + assertEquals("[-77, -10]", Arrays.toString("出".getBytes("gbk"))); + } + + public void test_compareTo() throws Exception { + // For strings where a character differs, the result is + // the difference between the characters. + assertEquals(-1, "a".compareTo("b")); + assertEquals(-2, "a".compareTo("c")); + assertEquals(1, "b".compareTo("a")); + assertEquals(2, "c".compareTo("a")); + + // For strings where the characters match up to the length of the shorter, + // the result is the difference between the strings' lengths. + assertEquals(0, "a".compareTo("a")); + assertEquals(-1, "a".compareTo("aa")); + assertEquals(-1, "a".compareTo("az")); + assertEquals(-2, "a".compareTo("aaa")); + assertEquals(-2, "a".compareTo("azz")); + assertEquals(-3, "a".compareTo("aaaa")); + assertEquals(-3, "a".compareTo("azzz")); + assertEquals(0, "a".compareTo("a")); + assertEquals(1, "aa".compareTo("a")); + assertEquals(1, "az".compareTo("a")); + assertEquals(2, "aaa".compareTo("a")); + assertEquals(2, "azz".compareTo("a")); + assertEquals(3, "aaaa".compareTo("a")); + assertEquals(3, "azzz".compareTo("a")); + } + + public void test_compareToIgnoreCase() throws Exception { + // For strings where a character differs, the result is + // the difference between the characters. + assertEquals(-1, "a".compareToIgnoreCase("b")); + assertEquals(-1, "a".compareToIgnoreCase("B")); + assertEquals(-2, "a".compareToIgnoreCase("c")); + assertEquals(-2, "a".compareToIgnoreCase("C")); + assertEquals(1, "b".compareToIgnoreCase("a")); + assertEquals(1, "B".compareToIgnoreCase("a")); + assertEquals(2, "c".compareToIgnoreCase("a")); + assertEquals(2, "C".compareToIgnoreCase("a")); + + // For strings where the characters match up to the length of the shorter, + // the result is the difference between the strings' lengths. + assertEquals(0, "a".compareToIgnoreCase("a")); + assertEquals(0, "a".compareToIgnoreCase("A")); + assertEquals(0, "A".compareToIgnoreCase("a")); + assertEquals(0, "A".compareToIgnoreCase("A")); + assertEquals(-1, "a".compareToIgnoreCase("aa")); + assertEquals(-1, "a".compareToIgnoreCase("aA")); + assertEquals(-1, "a".compareToIgnoreCase("Aa")); + assertEquals(-1, "a".compareToIgnoreCase("az")); + assertEquals(-1, "a".compareToIgnoreCase("aZ")); + assertEquals(-2, "a".compareToIgnoreCase("aaa")); + assertEquals(-2, "a".compareToIgnoreCase("AAA")); + assertEquals(-2, "a".compareToIgnoreCase("azz")); + assertEquals(-2, "a".compareToIgnoreCase("AZZ")); + assertEquals(-3, "a".compareToIgnoreCase("aaaa")); + assertEquals(-3, "a".compareToIgnoreCase("AAAA")); + assertEquals(-3, "a".compareToIgnoreCase("azzz")); + assertEquals(-3, "a".compareToIgnoreCase("AZZZ")); + assertEquals(1, "aa".compareToIgnoreCase("a")); + assertEquals(1, "aA".compareToIgnoreCase("a")); + assertEquals(1, "Aa".compareToIgnoreCase("a")); + assertEquals(1, "az".compareToIgnoreCase("a")); + assertEquals(2, "aaa".compareToIgnoreCase("a")); + assertEquals(2, "azz".compareToIgnoreCase("a")); + assertEquals(3, "aaaa".compareToIgnoreCase("a")); + assertEquals(3, "azzz".compareToIgnoreCase("a")); } } diff --git a/luni/src/test/java/libcore/java/lang/SystemTest.java b/luni/src/test/java/libcore/java/lang/SystemTest.java index f995954..ff155d3 100644 --- a/luni/src/test/java/libcore/java/lang/SystemTest.java +++ b/luni/src/test/java/libcore/java/lang/SystemTest.java @@ -16,14 +16,15 @@ package libcore.java.lang; -import junit.framework.TestCase; - import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Formatter; +import java.util.Properties; +import java.util.concurrent.atomic.AtomicBoolean; +import junit.framework.TestCase; public class SystemTest extends TestCase { @@ -33,11 +34,11 @@ public class SystemTest extends TestCase { // use System.getProperty. Now they should use System.lineSeparator instead, and the // "line.separator" property has no effect after the VM has started. - // Test System.lineSeparator directly. + // Test that System.lineSeparator is not changed when the corresponding + // system property is changed. assertEquals("\n", System.lineSeparator()); System.setProperty("line.separator", "poop"); assertEquals("\n", System.lineSeparator()); - assertFalse(System.lineSeparator().equals(System.getProperty("line.separator"))); // java.io.BufferedWriter --- uses System.lineSeparator on Android but not on RI. StringWriter sw = new StringWriter(); @@ -45,23 +46,19 @@ public class SystemTest extends TestCase { bw.newLine(); bw.flush(); assertEquals(System.lineSeparator(), sw.toString()); - assertFalse(System.lineSeparator().equals(System.getProperty("line.separator"))); // java.io.PrintStream --- uses System.lineSeparator on Android but not on RI. ByteArrayOutputStream baos = new ByteArrayOutputStream(); new PrintStream(baos).println(); assertEquals(System.lineSeparator(), new String(baos.toByteArray(), "UTF-8")); - assertFalse(System.lineSeparator().equals(System.getProperty("line.separator"))); // java.io.PrintWriter --- uses System.lineSeparator on Android but not on RI. sw = new StringWriter(); new PrintWriter(sw).println(); assertEquals(System.lineSeparator(), sw.toString()); - assertFalse(System.lineSeparator().equals(System.getProperty("line.separator"))); // java.util.Formatter --- uses System.lineSeparator on both. assertEquals(System.lineSeparator(), new Formatter().format("%n").toString()); - assertFalse(System.lineSeparator().equals(System.getProperty("line.separator"))); } finally { System.setProperty("line.separator", "\n"); } @@ -90,7 +87,7 @@ public class SystemTest extends TestCase { System.arraycopy(new char[5], 0, new Object[5], 0, 3); fail(); } catch (ArrayStoreException e) { - assertEquals("char[] and java.lang.Object[] are incompatible array types", e.getMessage()); + assertEquals("Incompatible types: src=char[], dst=java.lang.Object[]", e.getMessage()); } } @@ -118,4 +115,125 @@ public class SystemTest extends TestCase { assertEquals("dst == null", e.getMessage()); } } + + /** + * System.arraycopy() must never copy objects into arrays that can't store + * them. We've had bugs where type checks and copying were done separately + * and racy code could defeat the type checks. http://b/5247258 + */ + public void testArrayCopyConcurrentModification() { + final AtomicBoolean done = new AtomicBoolean(); + + final Object[] source = new Object[1024 * 1024]; + String[] target = new String[1024 * 1024]; + + new Thread() { + @Override public void run() { + // the last array element alternates between being a Thread and being null. When + // it's a Thread it isn't safe for arrayCopy; when its null it is! + while (!done.get()) { + source[source.length - 1] = this; + source[source.length - 1] = null; + } + } + }.start(); + + for (int i = 0; i < 8192; i++) { + try { + System.arraycopy(source, 0, target, 0, source.length); + assertNull(target[source.length - 1]); // make sure the wrong type didn't sneak in + } catch (ArrayStoreException ignored) { + } + } + + done.set(true); + } + + public void testSystemProperties_immutable() { + // Android-specific: The RI does not have a concept of immutable properties. + + // user.dir is an immutable property + String userDir = System.getProperty("user.dir"); + assertNotNull(userDir); + System.setProperty("user.dir", "not poop"); + assertEquals(userDir, System.getProperty("user.dir")); + + System.getProperties().setProperty("user.dir", "hmmph"); + assertEquals(userDir, System.getProperty("user.dir")); + + System.getProperties().clear(); + assertEquals(userDir, System.getProperty("user.dir")); + + Properties p = new Properties(); + p.setProperty("user.dir", "meh"); + System.setProperties(p); + + assertEquals(userDir, System.getProperty("user.dir")); + } + + public void testSystemProperties_mutable() { + // We allow "java.io.tmpdir" and "user.home" to be changed however + // we can't test for "java.io.tmpdir" consistently across test runners because + // it will be immutable if set on the dalvikvm command line "-Djava.io.tmpdir=" + // like vogar does. + String oldUserHome = System.getProperty("user.home"); + try { + System.setProperty("user.home", "/user/home"); + assertEquals("/user/home", System.getProperty("user.home")); + } finally { + System.setProperty("user.home", oldUserHome); + } + } + + public void testSystemProperties_setProperties_null() { + // user.dir is an immutable property + String userDir = System.getProperty("user.dir"); + assertNotNull(userDir); + + // Add a non-standard property + System.setProperty("p1", "v1"); + + // Reset using setProperties(null) + System.setProperties(null); + + // All the immutable properties should be reset. + assertEquals(userDir, System.getProperty("user.dir")); + // Non-standard properties are cleared. + assertNull(System.getProperty("p1")); + } + + public void testSystemProperties_setProperties_nonNull() { + String userDir = System.getProperty("user.dir"); + + Properties newProperties = new Properties(); + // Immutable property + newProperties.setProperty("user.dir", "v1"); + // Non-standard property + newProperties.setProperty("p1", "v2"); + + System.setProperties(newProperties); + + // Android-specific: The RI makes the setProperties() argument the system properties object, + // Android makes a new Properties object and copies the properties. + assertNotSame(newProperties, System.getProperties()); + // Android-specific: The RI does not have a concept of immutable properties. + assertEquals(userDir, System.getProperty("user.dir")); + + assertEquals("v2", System.getProperty("p1")); + } + + public void testSystemProperties_getProperties_clear() { + String userDir = System.getProperty("user.dir"); + assertNotNull(userDir); + System.setProperty("p1", "v1"); + + Properties properties = System.getProperties(); + assertEquals("v1", properties.getProperty("p1")); + + properties.clear(); + + // Android-specific: The RI clears everything, Android resets to immutable defaults. + assertEquals(userDir, System.getProperty("user.dir")); + assertNull(System.getProperty("p1")); + } } diff --git a/luni/src/test/java/libcore/java/lang/ThreadTest.java b/luni/src/test/java/libcore/java/lang/ThreadTest.java index 998afdb..8545a20 100644 --- a/luni/src/test/java/libcore/java/lang/ThreadTest.java +++ b/luni/src/test/java/libcore/java/lang/ThreadTest.java @@ -58,14 +58,71 @@ public final class ThreadTest extends TestCase { assertTrue("Unstarted threads were never finalized!", finalizedThreadsCount.get() > 0); } - private Thread newThread(final AtomicInteger finalizedThreadsCount, final int size) { - return new Thread() { - byte[] memoryPressure = new byte[size]; - @Override protected void finalize() throws Throwable { - super.finalize(); - finalizedThreadsCount.incrementAndGet(); - } - }; + public void testThreadSleep() throws Exception { + int millis = 1000; + long start = System.currentTimeMillis(); + + Thread.sleep(millis); + + long elapsed = System.currentTimeMillis() - start; + long offBy = Math.abs(elapsed - millis); + + assertTrue("Actual sleep off by " + offBy + " ms", offBy <= 250); + } + + public void testThreadInterrupted() throws Exception { + Thread.currentThread().interrupt(); + try { + Thread.sleep(0); + fail(); + } catch (InterruptedException e) { + assertFalse(Thread.currentThread().isInterrupted()); + } + } + + public void testThreadSleepIllegalArguments() throws Exception { + + try { + Thread.sleep(-1); + fail(); + } catch (IllegalArgumentException expected) { + } + + try { + Thread.sleep(0, -1); + fail(); + } catch (IllegalArgumentException expected) { + } + + try { + Thread.sleep(0, 1000000); + fail(); + } catch (IllegalArgumentException expected) { + } + } + + public void testThreadWakeup() throws Exception { + WakeupTestThread t1 = new WakeupTestThread(); + WakeupTestThread t2 = new WakeupTestThread(); + + t1.start(); + t2.start(); + assertTrue("Threads already finished", !t1.done && !t2.done); + + t1.interrupt(); + t2.interrupt(); + + Thread.sleep(1000); + assertTrue("Threads did not finish", t1.done && t2.done); + } + + public void testContextClassLoaderIsNotNull() { + assertNotNull(Thread.currentThread().getContextClassLoader()); + } + + public void testContextClassLoaderIsInherited() { + Thread other = new Thread(); + assertSame(Thread.currentThread().getContextClassLoader(), other.getContextClassLoader()); } /** @@ -109,4 +166,30 @@ public final class ThreadTest extends TestCase { // Expect to see the traces of all threads (not just t2) assertTrue("Must have traces for all threads", visibleTraces.get() > 1); } + + private Thread newThread(final AtomicInteger finalizedThreadsCount, final int size) { + return new Thread() { + long[] memoryPressure = new long[size]; + @Override protected void finalize() throws Throwable { + super.finalize(); + finalizedThreadsCount.incrementAndGet(); + } + }; + } + + private class WakeupTestThread extends Thread { + public boolean done; + + public void run() { + done = false; + + // Sleep for a while (1 min) + try { + Thread.sleep(60000); + } catch (InterruptedException ignored) { + } + + done = true; + } + } } diff --git a/luni/src/test/java/libcore/java/lang/reflect/AnnotationsTest.java b/luni/src/test/java/libcore/java/lang/reflect/AnnotationsTest.java index c23775e..4cc69ba 100644 --- a/luni/src/test/java/libcore/java/lang/reflect/AnnotationsTest.java +++ b/luni/src/test/java/libcore/java/lang/reflect/AnnotationsTest.java @@ -16,6 +16,7 @@ package libcore.java.lang.reflect; +import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; @@ -23,7 +24,11 @@ import java.lang.annotation.RetentionPolicy; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Constructor; import java.lang.reflect.Field; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.Proxy; import java.util.Arrays; import java.util.HashSet; import java.util.Set; @@ -56,7 +61,13 @@ public final class AnnotationsTest extends TestCase { public void testParameterAnnotations() throws Exception { Method method = Type.class.getMethod("method", String.class, String.class); - Annotation[][] parameterAnnotations = method.getParameterAnnotations(); + Annotation[][] noParameterAnnotations = method.getParameterAnnotations(); + assertEquals(2, noParameterAnnotations.length); + assertEquals(set(), annotationsToTypes(noParameterAnnotations[0])); + assertEquals(set(), annotationsToTypes(noParameterAnnotations[1])); + + Method parameters = Type.class.getMethod("parameters", String.class, String.class); + Annotation[][] parameterAnnotations = parameters.getParameterAnnotations(); assertEquals(2, parameterAnnotations.length); assertEquals(set(AnnotationB.class, AnnotationD.class), annotationsToTypes(parameterAnnotations[0])); @@ -64,6 +75,206 @@ public final class AnnotationsTest extends TestCase { annotationsToTypes(parameterAnnotations[1])); } + public void testAnnotationDefaults() throws Exception { + assertEquals((byte) 5, defaultValue("a")); + assertEquals((short) 6, defaultValue("b")); + assertEquals(7, defaultValue("c")); + assertEquals(8L, defaultValue("d")); + assertEquals(9.0f, defaultValue("e")); + assertEquals(10.0, defaultValue("f")); + assertEquals('k', defaultValue("g")); + assertEquals(true, defaultValue("h")); + assertEquals(Breakfast.WAFFLES, defaultValue("i")); + assertEquals("@" + AnnotationA.class.getName() + "()", defaultValue("j").toString()); + assertEquals("maple", defaultValue("k")); + assertEquals(AnnotationB.class, defaultValue("l")); + assertEquals("[1, 2, 3]", Arrays.toString((int[]) defaultValue("m"))); + assertEquals("[WAFFLES, PANCAKES]", Arrays.toString((Breakfast[]) defaultValue("n"))); + assertEquals(null, defaultValue("o")); + assertEquals(null, defaultValue("p")); + } + + private Object defaultValue(String name) throws NoSuchMethodException { + return HasDefaultsAnnotation.class.getMethod(name).getDefaultValue(); + } + + public void testGetEnclosingClass() { + assertNull(AnnotationsTest.class.getEnclosingClass()); + assertEquals(AnnotationsTest.class, Foo.class.getEnclosingClass()); + assertEquals(AnnotationsTest.class, HasMemberClassesInterface.class.getEnclosingClass()); + assertEquals(HasMemberClassesInterface.class, + HasMemberClassesInterface.D.class.getEnclosingClass()); + assertEquals(AnnotationsTest.class, Foo.class.getEnclosingClass()); + } + + public void testGetDeclaringClass() { + assertNull(AnnotationsTest.class.getDeclaringClass()); + assertEquals(AnnotationsTest.class, Foo.class.getDeclaringClass()); + assertEquals(AnnotationsTest.class, HasMemberClassesInterface.class.getDeclaringClass()); + assertEquals(HasMemberClassesInterface.class, + HasMemberClassesInterface.D.class.getDeclaringClass()); + } + + public void testGetEnclosingClassIsTransitiveForClassesDefinedInAMethod() { + class C {} + assertEquals(AnnotationsTest.class, C.class.getEnclosingClass()); + } + + public void testGetDeclaringClassIsNotTransitiveForClassesDefinedInAMethod() { + class C {} + assertEquals(null, C.class.getDeclaringClass()); + } + + public void testGetEnclosingMethodIsNotTransitive() { + class C { + class D {} + } + assertEquals(null, C.D.class.getEnclosingMethod()); + } + + public void testStaticFieldAnonymousClass() { + // The class declared in the <clinit> is enclosed by the <clinit>'s class. + // http://b/11245138 + assertEquals(AnnotationsTest.class, staticAnonymous.getClass().getEnclosingClass()); + // However, because it is anonymous, it has no declaring class. + // https://code.google.com/p/android/issues/detail?id=61003 + assertNull(staticAnonymous.getClass().getDeclaringClass()); + // Because the class is declared in <clinit> which is not exposed through reflection, + // it has no enclosing method or constructor. + assertNull(staticAnonymous.getClass().getEnclosingMethod()); + assertNull(staticAnonymous.getClass().getEnclosingConstructor()); + } + + public void testGetEnclosingMethodOfTopLevelClass() { + assertNull(AnnotationsTest.class.getEnclosingMethod()); + } + + public void testGetEnclosingConstructorOfTopLevelClass() { + assertNull(AnnotationsTest.class.getEnclosingConstructor()); + } + + public void testClassEnclosedByConstructor() throws Exception { + Foo foo = new Foo("string"); + assertEquals(Foo.class, foo.c.getEnclosingClass()); + assertEquals(Foo.class.getDeclaredConstructor(String.class), + foo.c.getEnclosingConstructor()); + assertNull(foo.c.getEnclosingMethod()); + assertNull(foo.c.getDeclaringClass()); + } + + public void testClassEnclosedByMethod() throws Exception { + Foo foo = new Foo(); + foo.foo("string"); + assertEquals(Foo.class, foo.c.getEnclosingClass()); + assertNull(foo.c.getEnclosingConstructor()); + assertEquals(Foo.class.getDeclaredMethod("foo", String.class), + foo.c.getEnclosingMethod()); + assertNull(foo.c.getDeclaringClass()); + } + + public void testGetClasses() throws Exception { + // getClasses() doesn't include classes inherited from interfaces! + assertSetEquals(HasMemberClasses.class.getClasses(), + HasMemberClassesSuperclass.B.class, HasMemberClasses.H.class); + } + + public void testGetDeclaredClasses() throws Exception { + assertSetEquals(HasMemberClasses.class.getDeclaredClasses(), + HasMemberClasses.G.class, HasMemberClasses.H.class, HasMemberClasses.I.class, + HasMemberClasses.J.class, HasMemberClasses.K.class, HasMemberClasses.L.class); + } + + public void testConstructorGetExceptions() throws Exception { + assertSetEquals(HasThrows.class.getConstructor().getExceptionTypes(), + IOException.class, InvocationTargetException.class, IllegalStateException.class); + assertSetEquals(HasThrows.class.getConstructor(Void.class).getExceptionTypes()); + } + + public void testClassMethodGetExceptions() throws Exception { + assertSetEquals(HasThrows.class.getMethod("foo").getExceptionTypes(), + IOException.class, InvocationTargetException.class, IllegalStateException.class); + assertSetEquals(HasThrows.class.getMethod("foo", Void.class).getExceptionTypes()); + } + + public void testProxyMethodGetExceptions() throws Exception { + InvocationHandler emptyInvocationHandler = new InvocationHandler() { + @Override public Object invoke(Object proxy, Method method, Object[] args) { + return null; + } + }; + + Object proxy = Proxy.newProxyInstance(getClass().getClassLoader(), + new Class[] { ThrowsInterface.class }, emptyInvocationHandler); + assertSetEquals(proxy.getClass().getMethod("foo").getExceptionTypes(), + IOException.class, InvocationTargetException.class, IllegalStateException.class); + assertSetEquals(proxy.getClass().getMethod("foo", Void.class).getExceptionTypes()); + } + + public void testClassModifiers() { + int modifiers = AnnotationsTest.class.getModifiers(); + assertTrue(Modifier.isPublic(modifiers)); + assertFalse(Modifier.isProtected(modifiers)); + assertFalse(Modifier.isPrivate(modifiers)); + assertFalse(Modifier.isAbstract(modifiers)); + assertFalse(Modifier.isStatic(modifiers)); + assertTrue(Modifier.isFinal(modifiers)); + assertFalse(Modifier.isStrict(modifiers)); + } + + public void testInnerClassModifiers() { + int modifiers = Foo.class.getModifiers(); + assertFalse(Modifier.isPublic(modifiers)); + assertFalse(Modifier.isProtected(modifiers)); + assertTrue(Modifier.isPrivate(modifiers)); + assertFalse(Modifier.isAbstract(modifiers)); + assertTrue(Modifier.isStatic(modifiers)); + assertFalse(Modifier.isFinal(modifiers)); + assertFalse(Modifier.isStrict(modifiers)); + } + + public void testAnonymousClassModifiers() { + int modifiers = staticAnonymous.getClass().getModifiers(); + assertFalse(Modifier.isPublic(modifiers)); + assertFalse(Modifier.isProtected(modifiers)); + assertFalse(Modifier.isPrivate(modifiers)); + assertFalse(Modifier.isAbstract(modifiers)); + assertTrue(Modifier.isStatic(modifiers)); + assertFalse(Modifier.isFinal(modifiers)); + assertFalse(Modifier.isStrict(modifiers)); + } + + public void testInnerClassName() { + assertEquals("AnnotationsTest", AnnotationsTest.class.getSimpleName()); + assertEquals("Foo", Foo.class.getSimpleName()); + assertEquals("", staticAnonymous.getClass().getSimpleName()); + } + + public void testIsAnonymousClass() { + assertFalse(AnnotationsTest.class.isAnonymousClass()); + assertFalse(Foo.class.isAnonymousClass()); + assertTrue(staticAnonymous.getClass().isAnonymousClass()); + } + + private static final Object staticAnonymous = new Object() {}; + + private static class Foo { + Class<?> c; + private Foo() { + } + private Foo(String s) { + c = new Object() {}.getClass(); + } + private Foo(int i) { + c = new Object() {}.getClass(); + } + private void foo(String s) { + c = new Object() {}.getClass(); + } + private void foo(int i) { + c = new Object() {}.getClass(); + } + } + @Retention(RetentionPolicy.RUNTIME) public @interface AnnotationA {} @@ -81,12 +292,68 @@ public final class AnnotationsTest extends TestCase { public static class Type { @AnnotationA @AnnotationC public Type() {} @AnnotationA @AnnotationD public String field; - @AnnotationB @AnnotationC public void method(@AnnotationB @AnnotationD String parameter1, + @AnnotationB @AnnotationC public void method(String parameter1, String parameter2) {} + @AnnotationB @AnnotationC public void parameters(@AnnotationB @AnnotationD String parameter1, @AnnotationC @AnnotationD String parameter2) {} } public static class ExtendsType extends Type {} + static enum Breakfast { WAFFLES, PANCAKES } + + @Retention(RetentionPolicy.RUNTIME) + public @interface HasDefaultsAnnotation { + byte a() default 5; + short b() default 6; + int c() default 7; + long d() default 8; + float e() default 9.0f; + double f() default 10.0; + char g() default 'k'; + boolean h() default true; + Breakfast i() default Breakfast.WAFFLES; + AnnotationA j() default @AnnotationA(); + String k() default "maple"; + Class l() default AnnotationB.class; + int[] m() default { 1, 2, 3 }; + Breakfast[] n() default { Breakfast.WAFFLES, Breakfast.PANCAKES }; + Breakfast o(); + int p(); + } + + static class HasMemberClassesSuperclass { + class A {} + public class B {} + static class C {} + } + + public interface HasMemberClassesInterface { + class D {} + public class E {} + static class F {} + } + + public static class HasMemberClasses extends HasMemberClassesSuperclass + implements HasMemberClassesInterface { + class G {} + public class H {} + static class I {} + enum J {} + interface K {} + @interface L {} + } + + public static class HasThrows { + public HasThrows() throws IOException, InvocationTargetException, IllegalStateException {} + public HasThrows(Void v) {} + public void foo() throws IOException, InvocationTargetException, IllegalStateException {} + public void foo(Void v) {} + } + + public static interface ThrowsInterface { + void foo() throws IOException, InvocationTargetException, IllegalStateException; + void foo(Void v); + } private void assertAnnotatedElement( AnnotatedElement element, Class<? extends Annotation>... expectedAnnotations) { @@ -134,4 +401,10 @@ public final class AnnotationsTest extends TestCase { private <T> Set<T> set(T... instances) { return new HashSet<T>(Arrays.asList(instances)); } + + private void assertSetEquals(Object[] actual, Object... expected) { + Set<Object> actualSet = new HashSet<Object>(Arrays.asList(actual)); + Set<Object> expectedSet = new HashSet<Object>(Arrays.asList(expected)); + assertEquals(expectedSet, actualSet); + } } diff --git a/luni/src/test/java/libcore/java/lang/reflect/ClassLoaderReflectionTest.java b/luni/src/test/java/libcore/java/lang/reflect/ClassLoaderReflectionTest.java index 2e15de2..28fd7e9 100644 --- a/luni/src/test/java/libcore/java/lang/reflect/ClassLoaderReflectionTest.java +++ b/luni/src/test/java/libcore/java/lang/reflect/ClassLoaderReflectionTest.java @@ -124,6 +124,28 @@ public final class ClassLoaderReflectionTest extends TestCase { assertParameterizedType(types[1], List.class, aClass); } + public void testClassesOfDifferentClassLoadersAreNotEqual() throws Exception { + assertFalse(A.class.equals(aClass)); + } + + public void testConstructorsOfDifferentClassLoadersAreNotEqual() throws Exception { + Constructor<?> c1 = A.class.getDeclaredConstructor(); + Constructor<?> c2 = aClass.getDeclaredConstructor(); + assertFalse(c1.equals(c2)); + } + + public void testMethodsOfDifferentClassLoadersAreNotEqual() throws Exception { + Method m1 = E.class.getMethod("call"); + Method m2 = eClass.getMethod("call"); + assertFalse(m1.equals(m2)); + } + + public void testFieldsOfDifferentClassLoadersAreNotEqual() throws Exception { + Field f1 = B.class.getDeclaredField("field"); + Field f2 = bClass.getDeclaredField("field"); + assertFalse(f1.equals(f2)); + } + static class A {} static class B<T> { T field; diff --git a/luni/src/test/java/libcore/java/lang/reflect/ConstructorTest.java b/luni/src/test/java/libcore/java/lang/reflect/ConstructorTest.java index ed98794..51ddfc0 100644 --- a/luni/src/test/java/libcore/java/lang/reflect/ConstructorTest.java +++ b/luni/src/test/java/libcore/java/lang/reflect/ConstructorTest.java @@ -72,6 +72,24 @@ public final class ConstructorTest extends TestCase { assertEquals(2, constructor.getParameterTypes().length); } + public void testEqualConstructorEqualsAndHashCode() throws Exception { + Constructor<?> c1 = ConstructorTestHelper.class.getConstructor(); + Constructor<?> c2 = ConstructorTestHelper.class.getConstructor(); + assertEquals(c1, c2); + assertEquals(c1.hashCode(), c2.hashCode()); + } + + public void testHashCodeSpec() throws Exception { + Constructor<?> c1 = ConstructorTestHelper.class.getConstructor(); + assertEquals(ConstructorTestHelper.class.getName().hashCode(), c1.hashCode()); + } + + public void testDifferentConstructorEqualsAndHashCode() throws Exception { + Constructor<?> c1 = ConstructorTestHelper.class.getConstructor(); + Constructor<?> c2 = ConstructorTestHelper.class.getConstructor(Object.class); + assertFalse(c1.equals(c2)); + } + static class ConstructorTestHelper { public ConstructorTestHelper() throws IndexOutOfBoundsException { } public ConstructorTestHelper(Object o) { } diff --git a/luni/src/test/java/libcore/java/lang/reflect/FieldTest.java b/luni/src/test/java/libcore/java/lang/reflect/FieldTest.java index eb3d034..b60d984 100644 --- a/luni/src/test/java/libcore/java/lang/reflect/FieldTest.java +++ b/luni/src/test/java/libcore/java/lang/reflect/FieldTest.java @@ -27,4 +27,27 @@ public final class FieldTest extends TestCase { Field field = getClass().getDeclaredField("MY_LONG"); assertEquals(5073258162644648461L, field.getLong(null)); } + + public void testEqualConstructorEqualsAndHashCode() throws Exception { + Field f1 = FieldTestHelper.class.getField("a"); + Field f2 = FieldTestHelper.class.getField("a"); + assertEquals(f1, f2); + assertEquals(f1.hashCode(), f2.hashCode()); + } + + public void testHashCodeSpec() throws Exception { + Field f1 = FieldTestHelper.class.getField("a"); + assertEquals(FieldTestHelper.class.getName().hashCode() ^ "a".hashCode(), f1.hashCode()); + } + + public void testDifferentConstructorEqualsAndHashCode() throws Exception { + Field f1 = FieldTestHelper.class.getField("a"); + Field f2 = FieldTestHelper.class.getField("b"); + assertFalse(f1.equals(f2)); + } + + static class FieldTestHelper { + public String a; + public Object b; + } } diff --git a/luni/src/test/java/libcore/java/lang/reflect/MethodTest.java b/luni/src/test/java/libcore/java/lang/reflect/MethodTest.java index ef30eb8..c3a436c 100644 --- a/luni/src/test/java/libcore/java/lang/reflect/MethodTest.java +++ b/luni/src/test/java/libcore/java/lang/reflect/MethodTest.java @@ -20,42 +20,6 @@ import java.lang.reflect.Method; import junit.framework.TestCase; public final class MethodTest extends TestCase { - // Check that the VM gives useful detail messages. - public void test_invokeExceptions() throws Exception { - Method m = String.class.getMethod("charAt", int.class); - try { - m.invoke("hello"); // Wrong number of arguments. - fail(); - } catch (IllegalArgumentException iae) { - assertEquals("wrong number of arguments; expected 1, got 0", iae.getMessage()); - } - try { - m.invoke("hello", "world"); // Wrong type. - fail(); - } catch (IllegalArgumentException iae) { - assertEquals("argument 1 should have type int, got java.lang.String", iae.getMessage()); - } - try { - m.invoke("hello", (Object) null); // Null for a primitive argument. - fail(); - } catch (IllegalArgumentException iae) { - assertEquals("argument 1 should have type int, got null", iae.getMessage()); - } - try { - m.invoke(new Integer(5)); // Wrong type for 'this'. - fail(); - } catch (IllegalArgumentException iae) { - assertEquals("expected receiver of type java.lang.String, but got java.lang.Integer", iae.getMessage()); - } - try { - m.invoke(null); // Null for 'this'. - fail(); - } catch (NullPointerException npe) { - assertEquals("expected receiver of type java.lang.String, but got null", - npe.getMessage()); - } - } - public void test_getExceptionTypes() throws Exception { Method method = MethodTestHelper.class.getMethod("m1", new Class[0]); Class[] exceptions = method.getExceptionTypes(); @@ -197,6 +161,26 @@ public final class MethodTest extends TestCase { assertEquals(anonymous.getClass(), method.getDeclaringClass()); } + public void testEqualMethodEqualsAndHashCode() throws Exception { + Method m1 = MethodTestHelper.class.getMethod("m1"); + Method m2 = MethodTestHelper.class.getMethod("m1"); + assertEquals(m1, m2); + assertEquals(m1.hashCode(), m2.hashCode()); + assertEquals(MethodTestHelper.class.getName().hashCode() ^ "m1".hashCode(), m1.hashCode()); + } + + public void testHashCodeSpec() throws Exception { + Method m1 = MethodTestHelper.class.getMethod("m1"); + assertEquals(MethodTestHelper.class.getName().hashCode() ^ "m1".hashCode(), m1.hashCode()); + } + + public void testDifferentMethodEqualsAndHashCode() throws Exception { + Method m1 = MethodTestHelper.class.getMethod("m1"); + Method m2 = MethodTestHelper.class.getMethod("m2", Object.class); + assertFalse(m1.equals(m2)); + assertFalse(m1.hashCode() == m2.hashCode()); + } + // http://b/1045939 public void testMethodToString() throws Exception { assertEquals("public final native void java.lang.Object.notify()", diff --git a/luni/src/test/java/libcore/java/lang/reflect/OldGenericReflectionCornerCases.java b/luni/src/test/java/libcore/java/lang/reflect/OldGenericReflectionCornerCases.java index 168a00d..ad3cc06 100644 --- a/luni/src/test/java/libcore/java/lang/reflect/OldGenericReflectionCornerCases.java +++ b/luni/src/test/java/libcore/java/lang/reflect/OldGenericReflectionCornerCases.java @@ -16,12 +16,12 @@ package libcore.java.lang.reflect; +import org.apache.harmony.tests.java.lang.reflect.GenericReflectionTestsBase; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; -import tests.api.java.lang.reflect.GenericReflectionTestsBase; /** * Tests generic reflection in more complicated cases. In particular: Scoping of diff --git a/luni/src/test/java/libcore/java/lang/reflect/OldGenericTypesTest.java b/luni/src/test/java/libcore/java/lang/reflect/OldGenericTypesTest.java index 69eff4f..9dec794 100644 --- a/luni/src/test/java/libcore/java/lang/reflect/OldGenericTypesTest.java +++ b/luni/src/test/java/libcore/java/lang/reflect/OldGenericTypesTest.java @@ -21,7 +21,7 @@ import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; -import tests.api.java.lang.reflect.GenericReflectionTestsBase; +import org.apache.harmony.tests.java.lang.reflect.GenericReflectionTestsBase; /** diff --git a/luni/src/test/java/libcore/java/lang/reflect/ProxyTest.java b/luni/src/test/java/libcore/java/lang/reflect/ProxyTest.java index 30d47fb..abd5851 100644 --- a/luni/src/test/java/libcore/java/lang/reflect/ProxyTest.java +++ b/luni/src/test/java/libcore/java/lang/reflect/ProxyTest.java @@ -16,14 +16,25 @@ package libcore.java.lang.reflect; +import java.io.EOFException; +import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; +import java.lang.reflect.UndeclaredThrowableException; +import java.net.SocketException; import junit.framework.TestCase; import tests.util.ClassLoaderBuilder; public final class ProxyTest extends TestCase { + private final ClassLoader loader = getClass().getClassLoader(); + private final InvocationHandler returnHandler = new TestInvocationHandler(); + private final InvocationHandler throwHandler = new InvocationHandler() { + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + throw (Throwable) args[0]; + } + }; /** * Make sure the proxy's class loader fails if it cannot see the class @@ -36,7 +47,7 @@ public final class ProxyTest extends TestCase { Class[] interfacesA = { loaderA.loadClass(prefix + "$Echo") }; try { - Proxy.newProxyInstance(loaderB, interfacesA, new TestInvocationHandler()); + Proxy.newProxyInstance(loaderB, interfacesA, returnHandler); fail(); } catch (IllegalArgumentException expected) { } @@ -55,10 +66,331 @@ public final class ProxyTest extends TestCase { assertEquals("foo", proxy.getClass().getMethod("echo", String.class).invoke(proxy, "foo")); } + public void testIncompatibleReturnTypesPrimitiveAndPrimitive() { + try { + Proxy.newProxyInstance(loader, new Class[] {ReturnsInt.class, ReturnsFloat.class}, + returnHandler); + fail(); + } catch (IllegalArgumentException expected) { + } + } + + public void testIncompatibleReturnTypesPrimitiveAndWrapper() { + try { + Proxy.newProxyInstance(loader, new Class[] {ReturnsInt.class, ReturnsInteger.class}, + returnHandler); + fail(); + } catch (IllegalArgumentException expected) { + } + } + + public void testIncompatibleReturnTypesPrimitiveAndVoid() { + try { + Proxy.newProxyInstance(loader, new Class[] {ReturnsInt.class, ReturnsVoid.class}, + returnHandler); + fail(); + } catch (IllegalArgumentException expected) { + } + } + + public void testIncompatibleReturnTypesIncompatibleObjects() { + try { + Proxy.newProxyInstance(loader, new Class[] {ReturnsInteger.class, ReturnsString.class }, + returnHandler); + fail(); + } catch (IllegalArgumentException expected) { + } + } + + public void testCompatibleReturnTypesImplementedInterface() { + Proxy.newProxyInstance(loader, new Class[] {ReturnsString.class, ReturnsCharSequence.class}, + returnHandler); + Proxy.newProxyInstance(loader, new Class[]{ReturnsObject.class, ReturnsCharSequence.class, + ReturnsString.class}, returnHandler); + Proxy.newProxyInstance(loader, new Class[]{ReturnsObject.class, ReturnsCharSequence.class, + ReturnsString.class, ReturnsSerializable.class, ReturnsComparable.class}, + returnHandler); + } + + + public void testCompatibleReturnTypesSuperclass() { + Proxy.newProxyInstance(loader, new Class[] {ReturnsString.class, ReturnsObject.class}, + returnHandler); + } + + public void testDeclaredExceptionIntersectionIsSubtype() throws Exception { + ThrowsIOException instance = (ThrowsIOException) Proxy.newProxyInstance(loader, + new Class[] {ThrowsIOException.class, ThrowsEOFException.class}, + throwHandler); + try { + instance.run(new EOFException()); + fail(); + } catch (EOFException expected) { + } + try { + instance.run(new IOException()); + fail(); + } catch (UndeclaredThrowableException expected) { + } + try { + instance.run(new Exception()); + fail(); + } catch (UndeclaredThrowableException expected) { + } + } + + public void testDeclaredExceptionIntersectionIsEmpty() throws Exception { + ThrowsEOFException instance = (ThrowsEOFException) Proxy.newProxyInstance(loader, + new Class[] {ThrowsSocketException.class, ThrowsEOFException.class}, + throwHandler); + try { + instance.run(new EOFException()); + fail(); + } catch (UndeclaredThrowableException expected) { + } + try { + instance.run(new SocketException()); + fail(); + } catch (UndeclaredThrowableException expected) { + } + } + + public void testDeclaredExceptionIntersectionIsSubset() throws Exception { + ThrowsEOFException instance = (ThrowsEOFException) Proxy.newProxyInstance(loader, + new Class[] {ThrowsEOFException.class, ThrowsSocketExceptionAndEOFException.class}, + throwHandler); + try { + instance.run(new EOFException()); + fail(); + } catch (EOFException expected) { + } + try { + instance.run(new SocketException()); + fail(); + } catch (UndeclaredThrowableException expected) { + } + try { + instance.run(new IOException()); + fail(); + } catch (UndeclaredThrowableException expected) { + } + } + + public void testDeclaredExceptionIntersectedByExactReturnTypes() throws Exception { + ThrowsIOException instance = (ThrowsIOException) Proxy.newProxyInstance(loader, + new Class[] {ThrowsIOException.class, ThrowsEOFExceptionReturnsString.class}, + throwHandler); + try { + instance.run(new EOFException()); + fail(); + } catch (EOFException expected) { + } + try { + instance.run(new IOException()); + fail(); + } catch (IOException expected) { + } + try { + ((ThrowsEOFExceptionReturnsString) instance).run(new EOFException()); + fail(); + } catch (EOFException expected) { + } + try { + ((ThrowsEOFExceptionReturnsString) instance).run(new IOException()); + fail(); + } catch (UndeclaredThrowableException expected) { + } + } + + public void test_getProxyClass_nullInterfaces() { + try { + Proxy.getProxyClass(loader, new Class<?>[] { null }); + fail(); + } catch (NullPointerException expected) { + } + + try { + Proxy.getProxyClass(loader, Echo.class, null); + fail(); + } catch (NullPointerException expected) { + } + } + + public void test_getProxyClass_duplicateInterfaces() { + try { + Proxy.getProxyClass(loader, Echo.class, Echo.class); + fail(); + } catch (IllegalArgumentException expected) { + } + } + + public void test_getProxyClass_caching() throws Exception { + Class<?> proxy1 = Proxy.getProxyClass(loader, Echo.class, ReturnsInt.class); + Class<?> proxy2 = Proxy.getProxyClass(loader, Echo.class, ReturnsInt.class); + Class<?> proxy3 = Proxy.getProxyClass(loader, ReturnsInt.class, Echo.class); + + assertSame(proxy1, proxy2); + assertTrue(!proxy2.equals(proxy3)); + } + + public void testMethodsImplementedByFarIndirectInterface() { + ExtendsExtendsDeclaresFiveMethods instance = (ExtendsExtendsDeclaresFiveMethods) + Proxy.newProxyInstance(loader, new Class[]{ExtendsExtendsDeclaresFiveMethods.class}, + returnHandler); + assertEquals("foo", instance.a("foo")); + assertEquals(0x12345678, instance.b(0x12345678)); + assertEquals(Double.MIN_VALUE, instance.c(Double.MIN_VALUE)); + assertEquals(null, instance.d(null)); + assertEquals(0x1234567890abcdefL, instance.e(0x1234567890abcdefL)); + } + + public void testEquals() { + InvocationHandler handler = new InvocationHandler() { + @Override public Object invoke(Object proxy, Method method, Object[] args) { + return args[0] == ProxyTest.class; // bogus as equals(), but good for testing + } + }; + Echo instance = (Echo) Proxy.newProxyInstance(loader, new Class[]{Echo.class}, handler); + assertTrue(instance.equals(ProxyTest.class)); + assertFalse(instance.equals(new Object())); + assertFalse(instance.equals(instance)); + assertFalse(instance.equals(null)); + } + + public void testHashCode() { + InvocationHandler handler = new InvocationHandler() { + @Override public Object invoke(Object proxy, Method method, Object[] args) { + return 0x12345678; + } + }; + Echo instance = (Echo) Proxy.newProxyInstance(loader, new Class[]{Echo.class}, handler); + assertEquals(0x12345678, instance.hashCode()); + } + + public void testToString() { + InvocationHandler handler = new InvocationHandler() { + @Override public Object invoke(Object proxy, Method method, Object[] args) { + return "foo"; + } + }; + Echo instance = (Echo) Proxy.newProxyInstance(loader, new Class[]{Echo.class}, handler); + assertEquals("foo", instance.toString()); + } + + public void testReturnTypeDoesNotSatisfyAllConstraintsWithLenientCaller() { + InvocationHandler handler = new InvocationHandler() { + @Override public Object invoke(Object proxy, Method method, Object[] args) { + assertEquals(Object.class, method.getReturnType()); + return Boolean.TRUE; // not the right type for 'ReturnsString' callers + } + }; + ReturnsObject returnsObject = (ReturnsObject) Proxy.newProxyInstance(loader, + new Class[] {ReturnsString.class, ReturnsObject.class}, handler); + assertEquals(true, returnsObject.foo()); + } + + public void testReturnTypeDoesNotSatisfyAllConstraintsWithStrictCaller() { + InvocationHandler handler = new InvocationHandler() { + @Override public Object invoke(Object proxy, Method method, Object[] args) { + assertEquals(String.class, method.getReturnType()); + return Boolean.TRUE; // not the right type for 'ReturnsString' callers + } + }; + ReturnsString returnsString = (ReturnsString) Proxy.newProxyInstance(loader, + new Class[] {ReturnsString.class, ReturnsObject.class}, handler); + try { + returnsString.foo(); + fail(); + } catch (ClassCastException expected) { + } + } + + public void testReturnsTypeAndInterfaceNotImplementedByThatType() { + try { + Proxy.newProxyInstance(loader, new Class[] {ReturnsString.class, ReturnsEcho.class}, + returnHandler); + fail(); + } catch (IllegalArgumentException expected) { + } + } + public interface Echo { String echo(String s); } + public interface ReturnsInt { + int foo(); + } + + public interface ReturnsFloat { + float foo(); + } + + public interface ReturnsInteger { + Integer foo(); + } + + public interface ReturnsString { + String foo(); + } + + public interface ReturnsCharSequence { + CharSequence foo(); + } + + public interface ReturnsSerializable { + CharSequence foo(); + } + + public interface ReturnsComparable { + CharSequence foo(); + } + + public interface ReturnsObject { + Object foo(); + } + + public interface ReturnsVoid { + void foo(); + } + + public interface ReturnsEcho { + Echo foo(); + } + + public interface ThrowsIOException { + Object run(Throwable toThrow) throws IOException; + } + + public interface ThrowsEOFException { + Object run(Throwable toThrow) throws EOFException; + } + + public interface ThrowsEOFExceptionReturnsString { + String run(Throwable toThrow) throws EOFException; + } + + public interface ThrowsSocketException { + Object run(Throwable toThrow) throws SocketException; + + } + public interface ThrowsSocketExceptionAndEOFException { + Object run(Throwable toThrow) throws SocketException, EOFException; + + } + + public interface DeclaresFiveMethods { + String a(String a); + int b(int b); + double c(double c); + Object d(Object d); + long e(long e); + } + public interface ExtendsDeclaresFiveMethods extends DeclaresFiveMethods { + } + public interface ExtendsExtendsDeclaresFiveMethods extends ExtendsDeclaresFiveMethods { + } + public static class TestInvocationHandler implements InvocationHandler { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return args[0]; diff --git a/luni/src/test/java/libcore/java/lang/reflect/ReflectionTest.java b/luni/src/test/java/libcore/java/lang/reflect/ReflectionTest.java index cdce405..1950bf3 100644 --- a/luni/src/test/java/libcore/java/lang/reflect/ReflectionTest.java +++ b/luni/src/test/java/libcore/java/lang/reflect/ReflectionTest.java @@ -24,6 +24,8 @@ import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; +import java.util.AbstractCollection; +import java.util.AbstractList; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -37,6 +39,27 @@ public final class ReflectionTest extends TestCase { String classB = "libcore.java.lang.reflect.ReflectionTest$B"; String classC = "libcore.java.lang.reflect.ReflectionTest$C"; + public void testClassGetSuperclass() { + assertEquals(AbstractList.class, ArrayList.class.getSuperclass()); + assertEquals(AbstractCollection.class, AbstractList.class.getSuperclass()); + assertEquals(AbstractCollection.class, AbstractList.class.getSuperclass()); + assertEquals(Object.class, AbstractCollection.class.getSuperclass()); + assertNull(Object.class.getSuperclass()); + } + + public void testPrimitiveGetSuperclass() { + assertNull(boolean.class.getSuperclass()); + assertNull(int.class.getSuperclass()); + assertNull(double.class.getSuperclass()); + assertNull(void.class.getSuperclass()); + } + + public void testInterfaceGetSuperclass() { + assertNull(Comparable.class.getSuperclass()); + assertNull(DefinesMember.class.getSuperclass()); + assertNull(ExtendsDefinesMember.class.getSuperclass()); + } + /** * http://code.google.com/p/android/issues/detail?id=6636 */ @@ -277,6 +300,36 @@ public final class ReflectionTest extends TestCase { assertEquals(1, count(names(fields), "field")); } + public void testIsLocalClass() { + A methodLevelAnonymous = new A() {}; + class Local {} + class $Local$1 {} + assertFalse(ReflectionTest.class.isLocalClass()); + assertFalse(A.class.isLocalClass()); + assertFalse($Dollar$1.class.isLocalClass()); + assertFalse(CLASS_LEVEL_ANONYMOUS.getClass().isLocalClass()); + assertFalse(methodLevelAnonymous.getClass().isLocalClass()); + assertTrue(Local.class.isLocalClass()); + assertTrue($Local$1.class.isLocalClass()); + assertFalse(int.class.isLocalClass()); + assertFalse(Object.class.isLocalClass()); + } + + public void testIsAnonymousClass() { + A methodLevelAnonymous = new A() {}; + class Local {} + class $Local$1 {} + assertFalse(ReflectionTest.class.isAnonymousClass()); + assertFalse(A.class.isAnonymousClass()); + assertFalse($Dollar$1.class.isAnonymousClass()); + assertTrue(CLASS_LEVEL_ANONYMOUS.getClass().isAnonymousClass()); + assertTrue(methodLevelAnonymous.getClass().isAnonymousClass()); + assertFalse(Local.class.isAnonymousClass()); + assertFalse($Local$1.class.isAnonymousClass()); + assertFalse(int.class.isAnonymousClass()); + assertFalse(Object.class.isAnonymousClass()); + } + /** * Class.isEnum() erroneously returned true for indirect descendants of * Enum. http://b/1062200. @@ -299,8 +352,10 @@ public final class ReflectionTest extends TestCase { assertNull(greenClass.getEnumConstants()); } + static class $Dollar$1 {} static class A {} static class AList extends ArrayList<A> {} + static A CLASS_LEVEL_ANONYMOUS = new A() {}; static class B extends Exception {} diff --git a/luni/src/test/java/libcore/java/math/BigIntegerTest.java b/luni/src/test/java/libcore/java/math/BigIntegerTest.java index 15a0dad..58c68a1 100644 --- a/luni/src/test/java/libcore/java/math/BigIntegerTest.java +++ b/luni/src/test/java/libcore/java/math/BigIntegerTest.java @@ -156,4 +156,32 @@ public class BigIntegerTest extends junit.framework.TestCase { assertTrue(b.isProbablePrime(100)); } } + + public void test_negativeValues_superfluousZeros() throws Exception { + byte[] trimmedBytes = new byte[] { + (byte) 0xae, (byte) 0x0f, (byte) 0xa1, (byte) 0x93 + }; + byte[] extraZeroesBytes = new byte[] { + (byte) 0xff, (byte) 0xae, (byte) 0x0f, (byte) 0xa1, (byte) 0x93 + }; + + BigInteger trimmed = new BigInteger(trimmedBytes); + BigInteger extraZeroes = new BigInteger(extraZeroesBytes); + + assertEquals(trimmed, extraZeroes); + } + + public void test_positiveValues_superfluousZeros() throws Exception { + byte[] trimmedBytes = new byte[] { + (byte) 0x2e, (byte) 0x0f, (byte) 0xa1, (byte) 0x93 + }; + byte[] extraZeroesBytes = new byte[] { + (byte) 0x00, (byte) 0x2e, (byte) 0x0f, (byte) 0xa1, (byte) 0x93 + }; + + BigInteger trimmed = new BigInteger(trimmedBytes); + BigInteger extraZeroes = new BigInteger(extraZeroesBytes); + + assertEquals(trimmed, extraZeroes); + } } diff --git a/luni/src/test/java/libcore/java/math/CSVTest.java b/luni/src/test/java/libcore/java/math/CSVTest.java new file mode 100644 index 0000000..9e151c3 --- /dev/null +++ b/luni/src/test/java/libcore/java/math/CSVTest.java @@ -0,0 +1,88 @@ +package libcore.java.math; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +/** + * Standard single-input test framework for csv math tests + */ +public abstract class CSVTest extends junit.framework.TestCase { + /* + * csv file should have the following format: + * function,expected_output,input,extra_info + * e.g. cos,-0x1.0000000000000p+0,0x1.921fb54442d18p+1,cos(pi) + * for two input: function,expected_output,input1,input2,extra + * vogar classpath: obj/JAVA_LIBRARIES/core-tests-support_intermediates/javalib.jar + */ + + /** + * This is a set of functions in java.Math/StrictMath that take two inputs. + * These functions will call run2InputTest; others will call runTest. + */ + protected static final Set<String> twoInputFunctions; + static { + Set<String> twoInFunc = new HashSet<String>(); + twoInFunc.add("atan2"); + twoInFunc.add("copySign"); + twoInFunc.add("hypot"); + twoInFunc.add("IEEEremainder"); + twoInFunc.add("max"); + twoInFunc.add("min"); + twoInFunc.add("nextAfter"); + twoInFunc.add("pow"); + twoInFunc.add("scalb"); + twoInputFunctions = Collections.unmodifiableSet(twoInFunc); + } + + void TestCSVInputs(String[] csvFileNames) throws Exception { + int totalTests = 0; + for (String csvFileName : csvFileNames) { + String line = ""; + BufferedReader br = null; + + try { + br = new BufferedReader(new InputStreamReader( + getClass().getResourceAsStream(csvFileName))); + while ((line = br.readLine()) != null) { + if (line.charAt(0) != '#') { + String[] testCase = line.split(","); + runTest(testCase); + totalTests++; + } + } + } finally { + if (br != null) { + br.close(); + } + } + } + System.out.println("Completed running " + totalTests + " tests"); + } + + protected void runTest(String[] testCase) throws Exception { + String function = testCase[0]; + double expectedOutput = Double.parseDouble(testCase[1]); + double input = Double.parseDouble(testCase[2]); + String extra = ""; + if (twoInputFunctions.contains(function)) { + double input2 = Double.parseDouble(testCase[3]); + if (testCase.length > 4) { + extra = testCase[4]; + } + run2InputTest(function, expectedOutput, input, input2, extra); + } else { + if (testCase.length > 3) { + extra = testCase[3]; + } + runTest(function, expectedOutput, input, extra); + } + } + + abstract void runTest(String func, double expectedOutput, double input, + String extra) throws Exception; + + abstract void run2InputTest(String func, double expectedOutput, double input1, double input2, String extra) throws Exception; +}
\ No newline at end of file diff --git a/luni/src/test/java/libcore/java/math/OldBigDecimalConvertTest.java b/luni/src/test/java/libcore/java/math/OldBigDecimalConvertTest.java index 8f01a17..4823798 100644 --- a/luni/src/test/java/libcore/java/math/OldBigDecimalConvertTest.java +++ b/luni/src/test/java/libcore/java/math/OldBigDecimalConvertTest.java @@ -251,10 +251,6 @@ public class OldBigDecimalConvertTest extends TestCase { assertTrue("incorrect byteValue", i == bNumber); } - /** - * @test java.math.BigDecimal#byteValue() Convert negative BigDesimal to - * byte type - */ public void test_ByteValueNeg() { String sNumber = "-127.56789"; int iNumber = -128; diff --git a/luni/src/test/java/libcore/java/math/RunCSVTests.java b/luni/src/test/java/libcore/java/math/RunCSVTests.java new file mode 100644 index 0000000..0c107f1 --- /dev/null +++ b/luni/src/test/java/libcore/java/math/RunCSVTests.java @@ -0,0 +1,109 @@ +package libcore.java.math; + +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +/** + * Tests functions in java.lang.Math + * Looks for the filenames in csvFileNames in tests/resources + * Tests functions and numbers found in those files. + * Run: vogar --classpath out/target/common/obj/JAVA_LIBRARIES/core-tests-support_intermediates/javalib.jar + * libcore/luni/src/test/java/libcore/java/math/RunCSVTests.java + */ +public class RunCSVTests extends CSVTest { + /** Stores ulps of error allowed for each function, if not 1 ulp.*/ + private static final Map<String, Double> UlpMap; + static { + final HashMap<String, Double> funcUlps = new HashMap<String, Double>(); + funcUlps.put("sinh", 2.5); + funcUlps.put("cosh", 2.5); + funcUlps.put("tanh", 2.5); + funcUlps.put("abs", 0.0); + funcUlps.put("signum", 0.0); + funcUlps.put("getExponent", 0.0); + funcUlps.put("toRadians", 0.0); + funcUlps.put("toDegrees", 0.0); + funcUlps.put("sqrt", 0.0); + funcUlps.put("ceil", 0.0); + funcUlps.put("floor", 0.0); + funcUlps.put("rint", 0.0); + funcUlps.put("atan2", 2.0); + funcUlps.put("round", 0.0); + funcUlps.put("max", 0.0); + funcUlps.put("min", 0.0); + funcUlps.put("copySign", 0.0); + funcUlps.put("nextAfter", 0.0); + funcUlps.put("scalb", 0.0); + UlpMap = Collections.unmodifiableMap(funcUlps); + } + + public static final String[] csvFileNames = { "/math_tests.csv", + "/math_important_numbers.csv", "/math_java_only.csv" }; + + public void test_csv() throws Exception { + this.TestCSVInputs(csvFileNames); + } + + /** + * Runs a standard single-input test using assertEquals. + * Allows error based on UlpMap, but defaults to 1 ulp. + */ + @Override + void runTest(String func, double expectedOutput, double input, String extra) + throws Exception { + Class<Math> mathClass = Math.class; + Method m = mathClass.getMethod(func, new Class[] { Double.TYPE }); + Object returnValue = m.invoke(null, input); + + double allowedError; + if (UlpMap.containsKey(func)) { + allowedError = UlpMap.get(func)*Math.ulp(expectedOutput); + } else { + allowedError = Math.ulp(expectedOutput); + } + + try { + assertEquals(extra + ": " + m + ": " + input + ": ", expectedOutput, + (double) returnValue, allowedError); + } catch (ClassCastException e) { + assertEquals(extra + ": " + m + ": " + input + ": ", (int) expectedOutput, + (int) returnValue, allowedError); + } + } + + /** + * Runs a 2-input test using assertEquals. + * Allows error based on UlpMap, but defaults to 1 ulp. + */ + @Override + void run2InputTest(String func, double expectedOutput, double input1, + double input2, String extra) throws Exception { + Class<Math> mathClass = Math.class; + Method m; + Object returnValue; + if (func.equals("scalb")) { + m = mathClass.getMethod(func, new Class[] { Double.TYPE, Integer.TYPE }); + returnValue = m.invoke(null, input1, (int) input2); + } else { + m = mathClass.getMethod(func, new Class[] { Double.TYPE, Double.TYPE }); + returnValue = m.invoke(null, input1, input2); + } + + double allowedError; + if (UlpMap.containsKey(func)) { + allowedError = UlpMap.get(func)*Math.ulp(expectedOutput); + } else { + allowedError = Math.ulp(expectedOutput); + } + + try { + assertEquals(extra + ": " + m + ": ", expectedOutput, (double) returnValue, + allowedError); + } catch (ClassCastException e) { + assertEquals(extra + ": " + m + ": ", (int) expectedOutput, (int) returnValue, + allowedError); + } + } +} diff --git a/luni/src/test/java/libcore/java/math/RunCSVTestsStrict.java b/luni/src/test/java/libcore/java/math/RunCSVTestsStrict.java new file mode 100644 index 0000000..0443eb0 --- /dev/null +++ b/luni/src/test/java/libcore/java/math/RunCSVTestsStrict.java @@ -0,0 +1,62 @@ +package libcore.java.math; + +import java.lang.reflect.Method; + +/** + * Tests java.lang.StrictMath + * Looks for the filenames in csvFileNames in tests/resources + * Tests functions and numbers found in those files. + * Run: vogar --classpath out/target/common/obj/JAVA_LIBRARIES/core-tests-support_intermediates/javalib.jar + * libcore/luni/src/test/java/libcore/java/math/RunCSVTestsStrict.java + */ +public class RunCSVTestsStrict extends CSVTest { + public static final String[] csvFileNames = { "/math_tests.csv", + "/math_important_numbers.csv", "/math_java_only.csv" }; + + public void test_csv() throws Exception { + this.TestCSVInputs(csvFileNames); + } + + /** + * Runs single-input test using assertEquals. + */ + @Override + void runTest(String func, double expectedOutput, double input, String extra) + throws Exception { + Class<StrictMath> mathClass = StrictMath.class; + Method m = mathClass.getMethod(func, new Class[] { Double.TYPE }); + Object returnValue = m.invoke(null, input); + + try { + assertEquals(extra + ": " + m + ": " + input + ": ", expectedOutput, + (double) returnValue, 0D); + } catch (ClassCastException e) { + assertEquals(extra + ": " + m + ": " + input + ": ", (int) expectedOutput, + (int) returnValue, 0D); + } + } + + /** + * Runs 2-input test using assertEquals. + */ + @Override + void run2InputTest(String func, double expectedOutput, double input1, + double input2, String extra) throws Exception { + Class<StrictMath> mathClass = StrictMath.class; + Method m; + Object returnValue; + if (func.equals("scalb")) { + m = mathClass.getMethod(func, new Class[] { Double.TYPE, Integer.TYPE }); + returnValue = m.invoke(null, input1, (int) input2); + } else { + m = mathClass.getMethod(func, new Class[] { Double.TYPE, Double.TYPE }); + returnValue = m.invoke(null, input1, input2); + } + + try { + assertEquals(extra + ": " + m + ": " , expectedOutput, (double) returnValue, 0D); + } catch (ClassCastException e) { + assertEquals(extra + ": " + m + ": ", (int) expectedOutput, (int) returnValue, 0D); + } + } +} diff --git a/luni/src/test/java/libcore/java/net/DatagramSocketTest.java b/luni/src/test/java/libcore/java/net/DatagramSocketTest.java new file mode 100644 index 0000000..86e47ec --- /dev/null +++ b/luni/src/test/java/libcore/java/net/DatagramSocketTest.java @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2014 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 junit.framework.TestCase; + +import java.net.DatagramSocket; +import java.net.InetSocketAddress; + +public class DatagramSocketTest extends TestCase { + + public void testInitialState() throws Exception { + DatagramSocket ds = new DatagramSocket(); + try { + assertTrue(ds.isBound()); + assertTrue(ds.getBroadcast()); // The RI starts DatagramSocket in broadcast mode. + assertFalse(ds.isClosed()); + assertFalse(ds.isConnected()); + assertTrue(ds.getLocalPort() > 0); + assertTrue(ds.getLocalAddress().isAnyLocalAddress()); + InetSocketAddress socketAddress = (InetSocketAddress) ds.getLocalSocketAddress(); + assertEquals(ds.getLocalPort(), socketAddress.getPort()); + assertEquals(ds.getLocalAddress(), socketAddress.getAddress()); + assertNull(ds.getInetAddress()); + assertEquals(-1, ds.getPort()); + assertNull(ds.getRemoteSocketAddress()); + assertFalse(ds.getReuseAddress()); + assertNull(ds.getChannel()); + } finally { + ds.close(); + } + } + + public void testStateAfterClose() throws Exception { + DatagramSocket ds = new DatagramSocket(); + ds.close(); + assertTrue(ds.isBound()); + assertTrue(ds.isClosed()); + assertFalse(ds.isConnected()); + assertNull(ds.getLocalAddress()); + assertEquals(-1, ds.getLocalPort()); + assertNull(ds.getLocalSocketAddress()); + } +} diff --git a/luni/src/test/java/libcore/java/net/InetAddressTest.java b/luni/src/test/java/libcore/java/net/InetAddressTest.java index c7617ab..4b656cc 100644 --- a/luni/src/test/java/libcore/java/net/InetAddressTest.java +++ b/luni/src/test/java/libcore/java/net/InetAddressTest.java @@ -49,13 +49,16 @@ public class InetAddressTest extends junit.framework.TestCase { "1234", "0", // Single out the deprecated form of the ANY address. - // Hex. + // Hex. Not supported by Android but supported by the RI. "0x1.0x2.0x3.0x4", "0x7f.0x00.0x00.0x01", "7f.0.0.1", - // Octal. - "0177.00.00.01", // Historically, this would have been interpreted as 127.0.0.1. + // Octal. Not supported by Android but supported by the RI. In the RI, if any of the numbers + // cannot be treated as a decimal the entire IP is interpreted differently, leading to + // "0177.00.00.01" -> 177.0.0.1, but "0177.0x0.00.01" -> 127.0.0.1. + // Android does not do this. + "0256.00.00.01", // Historically, this could have been interpreted as 174.0.0.1. // Negative numbers. "-1.0.0.1", @@ -89,6 +92,9 @@ public class InetAddressTest extends junit.framework.TestCase { } catch (IllegalArgumentException expected) { } + // Android does not recognize Octal (leading 0) cases: they are treated as decimal. + assertEquals("/177.0.0.1", InetAddress.parseNumericAddress("0177.00.00.01").toString()); + for (String invalid : INVALID_IPv4_NUMERIC_ADDRESSES) { try { InetAddress.parseNumericAddress(invalid); @@ -121,6 +127,9 @@ public class InetAddressTest extends junit.framework.TestCase { // Negative test assertFalse(InetAddress.isNumeric("example.com")); + // Android does not handle Octal (leading 0) cases: they are treated as decimal. + assertTrue(InetAddress.isNumeric("0177.00.00.01")); // Interpreted as 177.0.0.1 + for (String invalid : INVALID_IPv4_NUMERIC_ADDRESSES) { assertFalse(invalid, InetAddress.isNumeric(invalid)); } diff --git a/luni/src/test/java/libcore/java/net/InetSocketAddressTest.java b/luni/src/test/java/libcore/java/net/InetSocketAddressTest.java index 1cbcd1a..3bca8dc 100644 --- a/luni/src/test/java/libcore/java/net/InetSocketAddressTest.java +++ b/luni/src/test/java/libcore/java/net/InetSocketAddressTest.java @@ -140,13 +140,14 @@ public class InetSocketAddressTest extends TestCase { InetSocketAddress isa1 = new InetSocketAddress("localhost", 80); assertFalse(isa1.isUnresolved()); - InetSocketAddress sockAddr = new InetSocketAddress("unknown.host", 1000); + InetSocketAddress sockAddr = new InetSocketAddress("unknown.host.google.com", 1000); assertTrue(sockAddr.isUnresolved()); } public void test_getHostString() throws Exception { // When we have a hostname, we'll get it back because that doesn't cost a DNS lookup... InetSocketAddress hasHostname = InetSocketAddress.createUnresolved("some host", 1234); + assertTrue(hasHostname.isUnresolved()); assertEquals("some host", hasHostname.getHostString()); assertEquals("some host", hasHostname.getHostName()); // When we don't have a hostname, whether or not we do the reverse lookup is the difference diff --git a/luni/src/test/java/libcore/java/net/OldCookieHandlerTest.java b/luni/src/test/java/libcore/java/net/OldCookieHandlerTest.java index 249c326..0e11d50 100644 --- a/luni/src/test/java/libcore/java/net/OldCookieHandlerTest.java +++ b/luni/src/test/java/libcore/java/net/OldCookieHandlerTest.java @@ -16,6 +16,9 @@ package libcore.java.net; +import com.google.mockwebserver.MockResponse; +import com.google.mockwebserver.MockWebServer; + import java.io.IOException; import java.net.CookieHandler; import java.net.URI; @@ -27,65 +30,57 @@ import tests.support.Support_Configuration; public class OldCookieHandlerTest extends TestCase { - URI getURI, putURI; - String link = "http://" + Support_Configuration.SpecialInetTestAddress + "/"; - boolean isGetCalled = false; - boolean isPutCalled = false; - boolean completedSuccessfully = false; - public void test_CookieHandler() { assertNull(CookieHandler.getDefault()); } - public void test_get_put() { + public void test_get_put() throws Exception { MockCookieHandler mch = new MockCookieHandler(); CookieHandler defaultHandler = CookieHandler.getDefault(); - CookieHandler.setDefault(mch); - - class TestThread extends Thread { - public void run() { - try { - URL url = new URL(link); - URLConnection conn = url.openConnection(); - conn.getContent(); - url = new URL(link); - conn = url.openConnection(); - conn.getContent(); - completedSuccessfully = true; - } catch (Exception e) { - e.printStackTrace(); - } - } - } try { - TestThread thread = new TestThread(); + CookieHandler.setDefault(mch); - thread.start(); - try { - thread.join(); - } catch (InterruptedException e) { - fail("InterruptedException was thrown."); - } + MockWebServer server = new MockWebServer(); + server.play(); + server.enqueue(new MockResponse().addHeader("Set-Cookie2: a=\"android\"; " + + "Comment=\"this cookie is delicious\"; " + + "CommentURL=\"http://google.com/\"; " + + "Discard; " + + "Domain=\"" + server.getCookieDomain() + "\"; " + + "Max-Age=\"60\"; " + + "Path=\"/path\"; " + + "Port=\"80,443," + server.getPort() + "\"; " + + "Secure; " + + "Version=\"1\"")); - assertTrue(isGetCalled); - assertTrue(isPutCalled); - assertTrue(completedSuccessfully); + URLConnection connection = server.getUrl("/path/foo").openConnection(); + connection.getContent(); + + assertTrue(mch.wasGetCalled()); + assertTrue(mch.wasPutCalled()); } finally { CookieHandler.setDefault(defaultHandler); } } - class MockCookieHandler extends CookieHandler { + private static class MockCookieHandler extends CookieHandler { + private boolean getCalled = false; + private boolean putCalled = false; public Map get(URI uri, Map requestHeaders) throws IOException { - getURI = uri; - isGetCalled = true; + getCalled = true; return requestHeaders; } public void put(URI uri, Map responseHeaders) throws IOException { - putURI = uri; - isPutCalled = true; + putCalled = true; + } + + public boolean wasGetCalled() { + return getCalled; + } + public boolean wasPutCalled() { + return putCalled; } } } diff --git a/luni/src/test/java/libcore/java/net/OldDatagramSocketTest.java b/luni/src/test/java/libcore/java/net/OldDatagramSocketTest.java deleted file mode 100644 index d51d461..0000000 --- a/luni/src/test/java/libcore/java/net/OldDatagramSocketTest.java +++ /dev/null @@ -1,2183 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.io.InterruptedIOException; -import java.net.BindException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.DatagramSocketImpl; -import java.net.DatagramSocketImplFactory; -import java.net.Inet4Address; -import java.net.Inet6Address; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.NetworkInterface; -import java.net.PortUnreachableException; -import java.net.SocketAddress; -import java.net.SocketException; -import java.net.SocketTimeoutException; -import java.net.UnknownHostException; -import java.nio.channels.DatagramChannel; -import java.nio.channels.IllegalBlockingModeException; -import java.util.Date; -import java.util.Vector; -import tests.support.Support_Configuration; -import tests.support.Support_PortManager; - -public class OldDatagramSocketTest extends junit.framework./*Socket*/TestCase { - - java.net.DatagramSocket ds; - - java.net.DatagramPacket dp; - - DatagramSocket sds = null; - - String retval; - - String testString = "Test String"; - - boolean interrupted; - - class DatagramServer extends Thread { - - public DatagramSocket ms; - - boolean running = true; - - public volatile byte[] rbuf = new byte[512]; - - volatile DatagramPacket rdp = null; - - public void run() { - try { - while (running) { - try { - ms.receive(rdp); - // echo the packet back - ms.send(rdp); - } catch (java.io.InterruptedIOException e) { - Thread.yield(); - } - ; - } - ; - } catch (java.io.IOException e) { - System.out.println("DatagramServer server failed: " + e); - } finally { - ms.close(); - } - } - - public void stopServer() { - running = false; - } - - public DatagramServer(int aPort, InetAddress address) - throws java.io.IOException { - rbuf = new byte[512]; - rbuf[0] = -1; - rdp = new DatagramPacket(rbuf, rbuf.length); - ms = new DatagramSocket(aPort, address); - ms.setSoTimeout(2000); - } - } - - public void test_Constructor() { - // Test for method java.net.DatagramSocket() - try { - ds = new java.net.DatagramSocket(); - } catch (Exception e) { - fail("Could not create DatagramSocket : " + e.getMessage()); - } - - /* - SecurityManager sm = new SecurityManager() { - - public void checkPermission(Permission perm) { - } - - public void checkListen(int port) { - throw new SecurityException(); - } - }; - - SecurityManager oldSm = System.getSecurityManager(); - System.setSecurityManager(sm); - try { - new DatagramSocket(); - fail("SecurityException should be thrown."); - } catch (SecurityException e) { - // expected - } catch (SocketException e) { - fail("SocketException was thrown."); - } finally { - System.setSecurityManager(oldSm); - } - */ - } - - public void test_ConstructorI() { - // Test for method java.net.DatagramSocket(int) - try { - int portNumber = Support_PortManager.getNextPortForUDP(); - ds = new java.net.DatagramSocket(portNumber); - assertTrue("Created socket with incorrect port", - ds.getLocalPort() == portNumber); - } catch (Exception e) { - fail("Could not create DatagramSocket : " + e.getMessage()); - } - - /* - SecurityManager sm = new SecurityManager() { - - public void checkPermission(Permission perm) { - } - - public void checkListen(int port) { - throw new SecurityException(); - } - }; - - SecurityManager oldSm = System.getSecurityManager(); - System.setSecurityManager(sm); - try { - new DatagramSocket(8080); - fail("SecurityException should be thrown."); - } catch (SecurityException e) { - // expected - } catch (SocketException e) { - fail("SocketException was thrown."); - } finally { - System.setSecurityManager(oldSm); - } - */ - - try { - DatagramSocket ds = new java.net.DatagramSocket(1); - if (!("root".equals(System.getProperty("user.name")))) { - fail("SocketException was not thrown."); - } - } catch (SocketException e) { - //expected - } - - } - - public void test_ConstructorILjava_net_InetAddress() { - // Test for method java.net.DatagramSocket(int, java.net.InetAddress) - try { - int portNumber = Support_PortManager.getNextPortForUDP(); - ds = new java.net.DatagramSocket(portNumber, InetAddress - .getLocalHost()); - assertTrue("Created socket with incorrect port", - ds.getLocalPort() == portNumber); - assertTrue("Created socket with incorrect address", ds - .getLocalAddress().equals(InetAddress.getLocalHost())); - } catch (Exception e) { - fail("Could not create DatagramSocket : " + e.getMessage()); - } - - /* - SecurityManager sm = new SecurityManager() { - - public void checkPermission(Permission perm) { - } - - public void checkListen(int port) { - throw new SecurityException(); - } - }; - - SecurityManager oldSm = System.getSecurityManager(); - System.setSecurityManager(sm); - try { - new java.net.DatagramSocket(8080, InetAddress - .getLocalHost()); - fail("SecurityException should be thrown."); - } catch (SecurityException e) { - // expected - } catch (SocketException e) { - fail("SocketException was thrown."); - } catch (UnknownHostException e) { - fail("UnknownHostException was thrown."); - } finally { - System.setSecurityManager(oldSm); - } - */ - - try { - new java.net.DatagramSocket(1, InetAddress - .getLocalHost()); - fail("SocketException was not thrown."); - } catch(SocketException se) { - //expected - } catch (UnknownHostException e) { - fail("UnknownHostException was thrown."); - } - } - - public void test_close() { - // Test for method void java.net.DatagramSocket.close() - try { - int portNumber = Support_PortManager.getNextPortForUDP(); - ds = new java.net.DatagramSocket(portNumber); - dp = new DatagramPacket("Test String".getBytes(), 11, InetAddress - .getLocalHost(), 0); - ds.close(); - try { - ds.send(dp); - fail("IOException was not thrown."); - } catch(IOException ioe) { - //expected - } - } catch (Exception e) { - fail("Unexpected exception: " + e.getMessage()); - } - } - - public void test_connectLjava_net_InetAddressI() throws - UnknownHostException, SocketException { - try { - ds = new java.net.DatagramSocket(); - InetAddress inetAddress = InetAddress.getLocalHost(); - int portNumber = Support_PortManager.getNextPortForUDP(); - ds.connect(inetAddress, portNumber); - assertTrue("Incorrect InetAddress", ds.getInetAddress().equals( - inetAddress)); - assertTrue("Incorrect Port", ds.getPort() == portNumber); - ds.disconnect(); - } catch (Exception e) { - fail("Exception during test : " + e.getMessage()); - } - - System.out - .println("Running test_connectLjava_net_InetAddressI" + - "(DatagramSocketTest) with IPv6GlobalAddressJcl4: " - + Support_Configuration.IPv6GlobalAddressJcl4); - try { - ds = new java.net.DatagramSocket(); - InetAddress inetAddress = InetAddress - .getByName(Support_Configuration.IPv6GlobalAddressJcl4); - int portNumber = Support_PortManager.getNextPortForUDP(); - ds.connect(inetAddress, portNumber); - assertTrue("Incorrect InetAddress", ds.getInetAddress().equals( - inetAddress)); - assertTrue("Incorrect Port", ds.getPort() == portNumber); - ds.disconnect(); - } catch (Exception e) { - fail("Exception during test : " + e.getMessage()); - } - - try { - // Create a connected datagram socket to test - // PlainDatagramSocketImpl.peek() - InetAddress localHost = InetAddress.getLocalHost(); - DatagramSocket ds = new DatagramSocket(); - int port = ds.getLocalPort(); - ds.connect(localHost, port); - DatagramPacket send = new DatagramPacket(new byte[10], 10, - localHost, port); - ds.send(send); - DatagramPacket receive = new DatagramPacket(new byte[20], 20); - ds.setSoTimeout(2000); - ds.receive(receive); - ds.close(); - assertTrue("Wrong size: " + receive.getLength(), receive - .getLength() == 10); - assertTrue("Wrong receiver", receive.getAddress().equals(localHost)); - } catch (IOException e) { - fail("Unexpected IOException : " + e.getMessage()); - } - - class DatagramServer extends Thread { - - public DatagramSocket ms; - - boolean running = true; - - public byte[] rbuf = new byte[512]; - - DatagramPacket rdp = null; - - public void run() { - try { - while (running) { - try { - ms.receive(rdp); - // echo the packet back - ms.send(rdp); - } catch (java.io.InterruptedIOException e) { - Thread.yield(); - } - - } - - } catch (java.io.IOException e) { - System.out.println("Multicast server failed: " + e); - } finally { - ms.close(); - } - } - - public void stopServer() { - running = false; - } - - public DatagramServer(int aPort, InetAddress address) - throws java.io.IOException { - rbuf = new byte[512]; - rbuf[0] = -1; - rdp = new DatagramPacket(rbuf, rbuf.length); - ms = new DatagramSocket(aPort, address); - ms.setSoTimeout(2000); - } - } - - // validate that we get the PortUnreachable exception if we try to - // send a dgram to a server that is not running and then do a recv - try { - ds = new java.net.DatagramSocket(); - InetAddress inetAddress = InetAddress.getLocalHost(); - int portNumber = Support_PortManager.getNextPortForUDP(); - ds.connect(inetAddress, portNumber); - DatagramPacket send = new DatagramPacket(new byte[10], 10); - ds.send(send); - DatagramPacket receive = new DatagramPacket(new byte[20], 20); - ds.setSoTimeout(10000); - ds.receive(receive); - ds.close(); - fail( - "No PortUnreachableException when connected at native level on recv "); - } catch (Exception e) { - assertTrue( - "Wrong exception when trying to connect at native level on recv: " - + e.toString(), - (e instanceof PortUnreachableException)); - } - - // validate that we can send/receive with datagram sockets connected at - // the native level - DatagramServer server = null; - int[] ports = Support_PortManager.getNextPortsForUDP(3); - int serverPortNumber = ports[0]; - try { - InetAddress localHost = InetAddress.getLocalHost(); - DatagramSocket ds = new DatagramSocket(ports[1]); - DatagramSocket ds2 = new DatagramSocket(ports[2]); - - try { - server = new DatagramServer(serverPortNumber, localHost); - server.start(); - Thread.sleep(1000); - } catch (Exception e) { - fail( - "Failed to set up datagram server for native connected Dgram socket test "); - } - - int port = ds.getLocalPort(); - ds.connect(localHost, serverPortNumber); - - byte[] sendBytes = { 'T', 'e', 's', 't', 0 }; - DatagramPacket send = new DatagramPacket(sendBytes, - sendBytes.length); - ds.send(send); - DatagramPacket receive = new DatagramPacket(new byte[20], 20); - ds.setSoTimeout(2000); - ds.receive(receive); - ds.close(); - assertTrue("Wrong size data received: " + receive.getLength(), - receive.getLength() == sendBytes.length); - assertTrue("Wrong data received" - + new String(receive.getData(), 0, receive.getLength()) - + ":" + new String(sendBytes), new String( - receive.getData(), 0, receive.getLength()) - .equals(new String(sendBytes))); - assertTrue("Wrong receiver:" + receive.getAddress() + ":" - + localHost, receive.getAddress().equals(localHost)); - } catch (Exception e) { - fail( - "Unexpected exception when sending data on dgram connected at native level:" - + e.toString()); - } - - if (server != null) { - server.stopServer(); - } - - // validate that we can disconnect - try { - ds = new java.net.DatagramSocket(); - InetAddress inetAddress = InetAddress.getLocalHost(); - int portNumber = Support_PortManager.getNextPortForUDP(); - ds.connect(inetAddress, portNumber); - ds.disconnect(); - ds.close(); - } catch (Exception e) { - assertTrue("Unexpected exception when trying to connect at native" - + e.toString(), (e instanceof PortUnreachableException)); - } - - // validate that once connected we cannot send to another address - try { - ds = new java.net.DatagramSocket(); - InetAddress inetAddress = InetAddress.getLocalHost(); - int portNumber = Support_PortManager.getNextPortForUDP(); - ds.connect(inetAddress, portNumber); - DatagramPacket send = new DatagramPacket(new byte[10], 10, - inetAddress, portNumber + 1); - ds.send(send); - ds.close(); - fail( - "No Exception when trying to send to a different address on a connected socket "); - } catch (Exception e) { - assertTrue( - "Wrong exception when trying to send to a different address on a connected socket: " - + e.toString(), - (e instanceof IllegalArgumentException)); - } - - // validate that we can connect, then disconnect, then connect then - // send/recv - server = null; - ports = Support_PortManager.getNextPortsForUDP(3); - serverPortNumber = ports[0]; - try { - InetAddress localHost = InetAddress.getLocalHost(); - DatagramSocket ds = new DatagramSocket(ports[1]); - DatagramSocket ds2 = new DatagramSocket(ports[2]); - - try { - server = new DatagramServer(serverPortNumber, localHost); - server.start(); - Thread.sleep(1000); - } catch (Exception e) { - fail( - "Failed to set up datagram server for native connected Dgram socket test "); - } - - int port = ds.getLocalPort(); - ds.connect(localHost, serverPortNumber + 1); - ds.disconnect(); - ds.connect(localHost, serverPortNumber); - - byte[] sendBytes = { 'T', 'e', 's', 't', 0 }; - DatagramPacket send = new DatagramPacket(sendBytes, - sendBytes.length); - ds.send(send); - DatagramPacket receive = new DatagramPacket(new byte[20], 20); - ds.setSoTimeout(2000); - ds.receive(receive); - ds.close(); - assertTrue( - "connect/disconnect/connect - Wrong size data received: " - + receive.getLength(), - receive.getLength() == sendBytes.length); - assertTrue("connect/disconnect/connect - Wrong data received" - + new String(receive.getData(), 0, receive.getLength()) - + ":" + new String(sendBytes), new String( - receive.getData(), 0, receive.getLength()) - .equals(new String(sendBytes))); - assertTrue("connect/disconnect/connect - Wrong receiver:" - + receive.getAddress() + ":" + localHost, receive - .getAddress().equals(localHost)); - } catch (Exception e) { - fail( - "Unexpected exception when sending data on dgram connected at native level after connect/disconnect/connect:" - + e.toString()); - } - - if (server != null) { - server.stopServer(); - } - - // validate that we can connect/disconnect then send/recv to any address - server = null; - ports = Support_PortManager.getNextPortsForUDP(3); - serverPortNumber = ports[0]; - try { - InetAddress localHost = InetAddress.getLocalHost(); - DatagramSocket ds = new DatagramSocket(ports[1]); - DatagramSocket ds2 = new DatagramSocket(ports[2]); - - try { - server = new DatagramServer(serverPortNumber, localHost); - server.start(); - Thread.sleep(1000); - } catch (Exception e) { - fail( - "Failed to set up datagram server for native connected Dgram socket test "); - } - - int port = ds.getLocalPort(); - ds.connect(localHost, serverPortNumber + 1); - ds.disconnect(); - - byte[] sendBytes = { 'T', 'e', 's', 't', 0 }; - DatagramPacket send = new DatagramPacket(sendBytes, - sendBytes.length, localHost, serverPortNumber); - ds.send(send); - DatagramPacket receive = new DatagramPacket(new byte[20], 20); - ds.setSoTimeout(2000); - ds.receive(receive); - ds.close(); - assertTrue("connect/disconnect - Wrong size data received: " - + receive.getLength(), - receive.getLength() == sendBytes.length); - assertTrue("connect/disconnect - Wrong data received" - + new String(receive.getData(), 0, receive.getLength()) - + ":" + new String(sendBytes), new String( - receive.getData(), 0, receive.getLength()) - .equals(new String(sendBytes))); - assertTrue("connect/disconnect - Wrong receiver:" - + receive.getAddress() + ":" + localHost, receive - .getAddress().equals(localHost)); - } catch (Exception e) { - fail( - "Unexpected exception when sending data on dgram connected at native level after connect/disconnect:" - + e.toString()); - } - - if (server != null) { - server.stopServer(); - } - - // validate that we can connect on an allready connected socket and then - // send/recv - server = null; - ports = Support_PortManager.getNextPortsForUDP(3); - serverPortNumber = ports[0]; - try { - InetAddress localHost = InetAddress.getLocalHost(); - DatagramSocket ds = new DatagramSocket(ports[1]); - DatagramSocket ds2 = new DatagramSocket(ports[2]); - - try { - server = new DatagramServer(serverPortNumber, localHost); - server.start(); - Thread.sleep(1000); - } catch (Exception e) { - fail( - "Failed to set up datagram server for native connected Dgram socket test "); - } - - int port = ds.getLocalPort(); - ds.connect(localHost, serverPortNumber + 1); - ds.connect(localHost, serverPortNumber); - - byte[] sendBytes = { 'T', 'e', 's', 't', 0 }; - DatagramPacket send = new DatagramPacket(sendBytes, - sendBytes.length); - ds.send(send); - DatagramPacket receive = new DatagramPacket(new byte[20], 20); - ds.setSoTimeout(2000); - ds.receive(receive); - ds.close(); - assertTrue("connect/connect - Wrong size data received: " - + receive.getLength(), - receive.getLength() == sendBytes.length); - assertTrue("connect/connect - Wrong data received" - + new String(receive.getData(), 0, receive.getLength()) - + ":" + new String(sendBytes), new String( - receive.getData(), 0, receive.getLength()) - .equals(new String(sendBytes))); - assertTrue("connect/connect - Wrong receiver:" - + receive.getAddress() + ":" + localHost, receive - .getAddress().equals(localHost)); - } catch (Exception e) { - fail( - "Unexpected exception when sending data on dgram connected at native level after connect/connect: " - + e.toString()); - } - - if (server != null) { - server.stopServer(); - } - - // test for when we fail to connect at the native level. Even though we - // fail at the native level there is no way to return an exception so - // there should be no exception - try { - ds = new java.net.DatagramSocket(); - byte[] addressBytes = { 0, 0, 0, 0 }; - InetAddress inetAddress = InetAddress.getByAddress(addressBytes); - int portNumber = Support_PortManager.getNextPortForUDP(); - ds.connect(inetAddress, portNumber); - } catch (Exception e) { - fail( - "Unexcpected exception when trying to connect at native level with bad address for signature with no exception to be returned: " - + e.toString()); - } - - System.out - .println("Running test_connectLjava_net_InetAddressI(DatagramSocketTest) with IPv6 address"); - try { - ds = new java.net.DatagramSocket(); - byte[] addressBytes = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0 }; - InetAddress inetAddress = InetAddress - .getByAddress(addressBytes); - int portNumber = Support_PortManager.getNextPortForUDP(); - ds.connect(inetAddress, portNumber); - } catch (Exception e) { - fail( - "Unexcpected exception when trying to connect at native level with bad IPv6 address for signature with no exception to be returned: " - + e.toString()); - } - } - - public void test_disconnect() { - try { - ds = new java.net.DatagramSocket(); - InetAddress inetAddress = InetAddress.getLocalHost(); - int portNumber = Support_PortManager.getNextPortForUDP(); - ds.connect(inetAddress, portNumber); - ds.disconnect(); - assertNull("Incorrect InetAddress", ds.getInetAddress()); - assertEquals("Incorrect Port", -1, ds.getPort()); - } catch (Exception e) { - fail("Exception during test : " + e.getMessage()); - } - - System.out - .println("Running test_disconnect(DatagramSocketTest) with IPv6GlobalAddressJcl4: " - + Support_Configuration.IPv6GlobalAddressJcl4); - try { - ds = new java.net.DatagramSocket(); - InetAddress inetAddress = InetAddress - .getByName(Support_Configuration.IPv6GlobalAddressJcl4); - int portNumber = Support_PortManager.getNextPortForUDP(); - ds.connect(inetAddress, portNumber); - ds.disconnect(); - assertNull("Incorrect InetAddress", ds.getInetAddress()); - assertEquals("Incorrect Port", -1, ds.getPort()); - } catch (Exception e) { - fail("Exception during test : " + e.getMessage()); - } - } - - public void test_getInetAddress() { - Vector<InetAddress> ias = new Vector<InetAddress>(); - try { - ias.add(InetAddress.getLocalHost()); - ias.add(InetAddress - .getByName(Support_Configuration.IPv6GlobalAddressJcl4)); - ias.add(InetAddress - .getByName(Support_Configuration.InetTestAddress2)); - ias.add(InetAddress - .getByName(Support_Configuration.InetTestAddress2)); - ias.add(InetAddress - .getByName(Support_Configuration.InetTestIP)); - } catch(Exception e) { - fail("Unexpected exception was thrown: " + e.toString()); - } - - for(InetAddress ia:ias) { - int portNumber = Support_PortManager.getNextPortForUDP(); - DatagramSocket ds = null; - try { - ds = new DatagramSocket(); - ds.connect(ia, portNumber); - assertEquals(ia, ds.getInetAddress()); - assertEquals("" + ia, ia, ds.getInetAddress()); - } catch (SocketException e) { - fail("SocketException was thrown."); - } finally { - ds.disconnect(); - ds.close(); - } - } - - try { - assertNull(new DatagramSocket().getInetAddress()); - } catch (SocketException e) { - fail("SocketException was thrown."); - } - - } - - public void test_getLocalPort() { - // Test for method int java.net.DatagramSocket.getLocalPort() - try { - int portNumber = Support_PortManager.getNextPortForUDP(); - ds = new java.net.DatagramSocket(portNumber); - assertTrue("Returned incorrect port", - ds.getLocalPort() == portNumber); - } catch (Exception e) { - fail("Exception during getLocalAddress : " + e.getMessage()); - } - } - - public void test_getPort() { - try { - int portNumber = Support_PortManager.getNextPortForUDP(); - DatagramSocket theSocket = new DatagramSocket(portNumber); - assertEquals("Expected -1 for remote port as not connected", - -1, theSocket.getPort()); - - // now connect the socket and validate that we get the right port - theSocket.connect(InetAddress.getLocalHost(), portNumber); - assertTrue("getPort returned wrong value:" + theSocket.getPort() - + ":Expected:" + portNumber, - theSocket.getPort() == portNumber); - } catch (Exception e) { - fail("unexpected exception during getPort test : " + e.getMessage()); - } - } - - public void test_getReceiveBufferSize() throws Exception { - int portNumber = Support_PortManager.getNextPortForUDP(); - ds = new java.net.DatagramSocket(portNumber); - ds.setReceiveBufferSize(130); - assertTrue("Incorrect buffer size", ds.getReceiveBufferSize() >= 130); - ds.close(); - try { - ds.getReceiveBufferSize(); - fail("SocketException was not thrown."); - } catch(SocketException se) { - //expected - } - } - - public void test_getSendBufferSize() throws Exception { - int portNumber = Support_PortManager.getNextPortForUDP(); - ds = new java.net.DatagramSocket(portNumber); - ds.setSendBufferSize(134); - assertTrue("Incorrect buffer size", ds.getSendBufferSize() >= 134); - ds.close(); - try { - ds.getSendBufferSize(); - fail("SocketException was not thrown."); - } catch(SocketException se) { - //expected - } - } - - public void test_getSoTimeout_setSoTimeout() throws Exception { - // TODO: a useful test would check that setSoTimeout actually causes timeouts! - DatagramSocket s = new DatagramSocket(); - s.setSoTimeout(1500); - int ms = s.getSoTimeout(); - if (ms < 1500-10 || ms > 1500+10) { - fail("suspicious timeout: " + ms); - } - s.close(); - try { - s.getSoTimeout(); - fail("SocketException was not thrown."); - } catch (SocketException expected) { - } - try { - s.setSoTimeout(1000); - fail("SocketException was not thrown."); - } catch (SocketException expected) { - } - } - - public void test_receiveLjava_net_DatagramPacket() throws Exception { - // Test for method void - // java.net.DatagramSocket.receive(java.net.DatagramPacket) - - receive_oversize_java_net_DatagramPacket(); - final int[] ports = Support_PortManager.getNextPortsForUDP(2); - final int portNumber = ports[0]; - - class TestDGRcv implements Runnable { - public void run() { - try { - InetAddress localHost = InetAddress.getLocalHost(); - Thread.sleep(1000); - DatagramSocket sds = new DatagramSocket(ports[1]); - sds.send(new DatagramPacket("Test".getBytes("UTF-8"), "Test".length(), localHost, portNumber)); - sds.send(new DatagramPacket("Longer test".getBytes("UTF-8"), "Longer test".length(), localHost, portNumber)); - sds.send(new DatagramPacket("3 Test".getBytes("UTF-8"), "3 Test".length(), localHost, portNumber)); - sds.send(new DatagramPacket("4 Test".getBytes("UTF-8"), "4 Test".length(), localHost, portNumber)); - sds.send(new DatagramPacket("5".getBytes("UTF-8"), "5".length(), localHost, portNumber)); - sds.close(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - } - - try { - new Thread(new TestDGRcv(), "datagram receiver").start(); - ds = new java.net.DatagramSocket(portNumber); - ds.setSoTimeout(6000); - byte[] rbuf = new byte[1000]; - DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length); - - // Receive the first packet. - ds.receive(rdp); - assertEquals("Test", new String(rbuf, 0, rdp.getLength())); - // Check that we can still receive a longer packet (http://code.google.com/p/android/issues/detail?id=24748). - ds.receive(rdp); - assertEquals("Longer test", new String(rbuf, 0, rdp.getLength())); - // See what happens if we manually call DatagramPacket.setLength. - rdp.setLength(4); - ds.receive(rdp); - assertEquals("3 Te", new String(rbuf, 0, rdp.getLength())); - // And then another. - ds.receive(rdp); - assertEquals("4 Te", new String(rbuf, 0, rdp.getLength())); - // And then a packet shorter than the user-supplied length. - ds.receive(rdp); - assertEquals("5", new String(rbuf, 0, rdp.getLength())); - - ds.close(); - } finally { - ds.close(); - } - DatagramSocket socket = null; - try { - byte rbuf[] = new byte[1000]; - DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length); - DatagramChannel channel = DatagramChannel.open(); - channel.configureBlocking(false); - socket = channel.socket(); - socket.receive(rdp); - fail("IllegalBlockingModeException was not thrown."); - } catch(IllegalBlockingModeException expected) { - } finally { - socket.close(); - } - - try { - ds = new java.net.DatagramSocket(portNumber); - ds.setSoTimeout(1000); - byte rbuf[] = new byte[1000]; - DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length); - ds.receive(rdp); - fail("SocketTimeoutException was not thrown."); - } catch(SocketTimeoutException expected) { - } finally { - ds.close(); - } - - interrupted = false; - final DatagramSocket ds = new DatagramSocket(); - ds.setSoTimeout(12000); - Runnable runnable = new Runnable() { - public void run() { - try { - ds.receive(new DatagramPacket(new byte[1], 1)); - } catch (InterruptedIOException e) { - interrupted = true; - } catch (IOException ignored) { - } - } - }; - Thread thread = new Thread(runnable, "DatagramSocket.receive1"); - thread.start(); - do { - Thread.sleep(500); - } while (!thread.isAlive()); - ds.close(); - int c = 0; - do { - Thread.sleep(500); - if (interrupted) { - fail("received interrupt"); - } - if (++c > 4) { - fail("read call did not exit"); - } - } while (thread.isAlive()); - - interrupted = false; - final int portNum = ports[0]; - final DatagramSocket ds2 = new DatagramSocket(ports[1]); - ds2.setSoTimeout(12000); - Runnable runnable2 = new Runnable() { - public void run() { - try { - ds2.receive(new DatagramPacket(new byte[1], 1, - InetAddress.getLocalHost(), portNum)); - } catch (InterruptedIOException e) { - interrupted = true; - } catch (IOException ignored) { - } - } - }; - Thread thread2 = new Thread(runnable2, "DatagramSocket.receive2"); - thread2.start(); - try { - do { - Thread.sleep(500); - } while (!thread2.isAlive()); - } catch (InterruptedException ignored) { - } - ds2.close(); - int c2 = 0; - do { - Thread.sleep(500); - if (interrupted) { - fail("receive2 was interrupted"); - } - if (++c2 > 4) { - fail("read2 call did not exit"); - } - } while (thread2.isAlive()); - - interrupted = false; - DatagramSocket ds3 = new DatagramSocket(); - ds3.setSoTimeout(500); - Date start = new Date(); - try { - ds3.receive(new DatagramPacket(new byte[1], 1)); - } catch (InterruptedIOException e) { - interrupted = true; - } - ds3.close(); - assertTrue("receive not interrupted", interrupted); - int delay = (int) (new Date().getTime() - start.getTime()); - assertTrue("timeout too soon: " + delay, delay >= 490); - } - - public void test_sendLjava_net_DatagramPacket() throws Exception { - // Test for method void - // java.net.DatagramSocket.send(java.net.DatagramPacket) - int[] ports = Support_PortManager.getNextPortsForUDP(2); - final int portNumber = ports[0]; - - class TestDGSend implements Runnable { - Thread pThread; - - public TestDGSend(Thread t) { - pThread = t; - } - - public void run() { - try { - byte[] rbuf = new byte[1000]; - - sds = new DatagramSocket(portNumber); - DatagramPacket sdp = new DatagramPacket(rbuf, rbuf.length); - sds.setSoTimeout(6000); - sds.receive(sdp); - retval = new String(rbuf, 0, testString.length()); - pThread.interrupt(); - } catch (java.io.InterruptedIOException e) { - System.out.println("Recv operation timed out"); - pThread.interrupt(); - ds.close(); - } catch (Exception e) { - System.out.println("Failed to establish Dgram server: " + e); - } - } - } - try { - new Thread(new TestDGSend(Thread.currentThread()), "DGServer") - .start(); - ds = new java.net.DatagramSocket(ports[1]); - dp = new DatagramPacket(testString.getBytes(), testString.length(), - InetAddress.getLocalHost(), portNumber); - // Wait to allow send to occur - try { - Thread.sleep(500); - ds.send(dp); - Thread.sleep(5000); - } catch (InterruptedException e) { - ds.close(); - assertTrue("Incorrect data sent: " + retval, retval - .equals(testString)); - } - } catch (Exception e) { - fail("Exception during send test : " + e.getMessage()); - } finally { - ds.close(); - } - - /* - SecurityManager sm = new SecurityManager() { - - public void checkPermission(Permission perm) { - } - - public void checkMulticast(InetAddress maddr) { - throw new SecurityException(); - } - - public void checkConnect(String host, - int port) { - throw new SecurityException(); - } - }; - try { - - ds = new java.net.DatagramSocket(ports[1]); - dp = new DatagramPacket(testString.getBytes(), testString.length(), - InetAddress.getLocalHost(), portNumber); - - SecurityManager oldSm = System.getSecurityManager(); - System.setSecurityManager(sm); - try { - ds.send(dp); - fail("SecurityException should be thrown."); - } catch (SecurityException e) { - // expected - } catch (SocketException e) { - fail("SocketException was thrown."); - } finally { - System.setSecurityManager(oldSm); - } - } catch(Exception e) { - fail("Unexpected exception was thrown: " + e.getMessage()); - } - */ - - DatagramSocket socket = null; - try { - byte rbuf[] = new byte[1000]; - DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length); - SocketAddress address = new InetSocketAddress(portNumber); - DatagramChannel channel = DatagramChannel.open(); - channel.configureBlocking(false); - socket = channel.socket(); - socket.send(rdp); - fail("IllegalBlockingModeException was not thrown."); - } catch(IllegalBlockingModeException ibme) { - //expected - } catch(IOException ioe) { - fail("IOException was thrown: " + ioe.getMessage()); - } finally { - socket.close(); - } - - //Regression for HARMONY-1118 - class testDatagramSocket extends DatagramSocket { - public testDatagramSocket(DatagramSocketImpl impl){ - super(impl); - } - } - class testDatagramSocketImpl extends DatagramSocketImpl { - protected void create() throws SocketException {} - protected void bind(int arg0, InetAddress arg1) throws SocketException {} - protected void send(DatagramPacket arg0) throws IOException {} - protected int peek(InetAddress arg0) throws IOException { - return 0; - } - protected int peekData(DatagramPacket arg0) throws IOException { - return 0; - } - protected void receive(DatagramPacket arg0) throws IOException {} - protected void setTTL(byte arg0) throws IOException {} - protected byte getTTL() throws IOException { - return 0; - } - protected void setTimeToLive(int arg0) throws IOException {} - protected int getTimeToLive() throws IOException { - return 0; - } - protected void join(InetAddress arg0) throws IOException {} - protected void leave(InetAddress arg0) throws IOException {} - protected void joinGroup(SocketAddress arg0, NetworkInterface arg1) throws IOException {} - protected void leaveGroup(SocketAddress arg0, NetworkInterface arg1) throws IOException {} - protected void close() {} - public void setOption(int arg0, Object arg1) throws SocketException {} - public Object getOption(int arg0) throws SocketException { - return null; - } - } - InetSocketAddress sa = new InetSocketAddress(InetAddress.getLocalHost(), 0); - //no exception expected for next line - new testDatagramSocket(new testDatagramSocketImpl()).send(new DatagramPacket(new byte[272], 3, sa)); - - // Regression test for Harmony-2938 - InetAddress i = InetAddress.getByName("127.0.0.1"); - DatagramSocket d = new DatagramSocket(0, i); - try { - d.send(new DatagramPacket(new byte[] { 1 }, 1)); - fail("should throw NPE."); - } catch (NullPointerException e) { - // expected; - } finally { - d.close(); - } - } - - public void test_setSendBufferSizeI() throws Exception { - int portNumber = Support_PortManager.getNextPortForUDP(); - ds = new java.net.DatagramSocket(portNumber); - ds.setSendBufferSize(134); - assertTrue("Incorrect buffer size", ds.getSendBufferSize() >= 134); - ds.close(); - try { - ds.setSendBufferSize(1); - fail("SocketException was not thrown."); - } catch(SocketException se) { - //expected - } - } - - public void test_setReceiveBufferSizeI() throws Exception { - int portNumber = Support_PortManager.getNextPortForUDP(); - ds = new java.net.DatagramSocket(portNumber); - ds.setReceiveBufferSize(130); - assertTrue("Incorrect buffer size", ds.getReceiveBufferSize() >= 130); - - try { - ds.setReceiveBufferSize(0); - fail("IllegalArgumentException was not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - - try { - ds.setReceiveBufferSize(-1); - fail("IllegalArgumentException was not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - - ds.close(); - - try { - ds.setReceiveBufferSize(1); - fail("SocketException was not thrown."); - } catch (SocketException e) { - //expected - } - } - - public void test_ConstructorLjava_net_DatagramSocketImpl() { - class testDatagramSocket extends DatagramSocket { - public testDatagramSocket(DatagramSocketImpl impl){ - super(impl); - } - } - - try { - new testDatagramSocket((DatagramSocketImpl) null); - fail("exception expected"); - } catch (NullPointerException ex) { - //expected - } - } - - public void test_ConstructorLjava_net_SocketAddress() { - class mySocketAddress extends SocketAddress { - - public mySocketAddress() { - } - } - - try { - try { - int portNumber = Support_PortManager.getNextPortForUDP(); - ds = new java.net.DatagramSocket(new InetSocketAddress( - InetAddress.getLocalHost(), portNumber)); - assertTrue(ds.getBroadcast()); - assertTrue("Created socket with incorrect port", ds - .getLocalPort() == portNumber); - assertTrue("Created socket with incorrect address", ds - .getLocalAddress().equals(InetAddress.getLocalHost())); - } catch (Exception e) { - fail("Could not create DatagramSocket : " + e.getMessage()); - } - - try { - int portNumber = Support_PortManager.getNextPortForUDP(); - ds = new java.net.DatagramSocket(new mySocketAddress()); - fail( - "No exception when constucting datagramSocket with unsupported SocketAddress type"); - } catch (IllegalArgumentException e) { - - } - //regression for Harmony-894 - ds = new DatagramSocket((SocketAddress)null); - assertTrue(ds.getBroadcast()); - } catch (Exception ex) { - fail( - "unexpected exception when datagramSocket SocketAddress constructor test"); - } - - /* - SecurityManager sm = new SecurityManager() { - - public void checkPermission(Permission perm) { - } - - public void checkListen(int port) { - throw new SecurityException(); - } - }; - - SecurityManager oldSm = System.getSecurityManager(); - System.setSecurityManager(sm); - try { - new DatagramSocket(new InetSocketAddress( - InetAddress.getLocalHost(), 1)); - fail("SecurityException should be thrown."); - } catch (SecurityException e) { - // expected - } catch (SocketException e) { - fail("SocketException was thrown."); - } catch (UnknownHostException e) { - fail("UnknownHostException was thrown."); - } finally { - System.setSecurityManager(oldSm); - } - */ - - InetSocketAddress isa = null; - try { - isa = new InetSocketAddress( - InetAddress.getLocalHost(), 1); - } catch (UnknownHostException e) { - fail("UnknownHostException was thrown."); - } - } - - public void test_bindLjava_net_SocketAddress() throws Exception { - int[] ports = Support_PortManager.getNextPortsForUDP(3); - int serverPortNumber = ports[1]; - - // now create a socket that is not bound and then bind it - InetAddress localHost = InetAddress.getLocalHost(); - InetSocketAddress localAddress1 = new InetSocketAddress(localHost, ports[0]); - DatagramSocket theSocket = new DatagramSocket(localAddress1); - - // validate that the localSocketAddress reflects the address we bound to - assertEquals(localAddress1, theSocket.getLocalSocketAddress()); - - // now make sure that datagrams sent from this socket appear to come - // from the address we bound to - InetSocketAddress localAddress2 = new InetSocketAddress(localHost, ports[2]); - DatagramSocket ds = new DatagramSocket((SocketAddress) null); - ds.bind(localAddress2); - - DatagramServer server = new DatagramServer(serverPortNumber, localHost); - server.start(); - Thread.sleep(1000); - - ds.connect(new InetSocketAddress(localHost, serverPortNumber)); - - byte[] sendBytes = { 'T', 'e', 's', 't', 0 }; - DatagramPacket send = new DatagramPacket(sendBytes, sendBytes.length); - ds.send(send); - Thread.sleep(1000); - ds.close(); - // Check that the address in the packet matches the bound address. - assertEquals(localAddress2, server.rdp.getSocketAddress()); - - if (server != null) { - server.stopServer(); - } - } - - public void test_bindLjava_net_SocketAddress_null() throws Exception { - // validate if we pass in null that it picks an address for us. - DatagramSocket theSocket = new DatagramSocket((SocketAddress) null); - theSocket.bind(null); - assertNotNull(theSocket.getLocalSocketAddress()); - theSocket.close(); - } - - public void test_bindLjava_net_SocketAddress_bad_address() throws Exception { - // Address we cannot bind to - DatagramSocket theSocket = new DatagramSocket((SocketAddress) null); - try { - InetAddress badAddress = InetAddress.getByAddress(Support_Configuration.nonLocalAddressBytes); - theSocket.bind(new InetSocketAddress(badAddress, Support_PortManager.getNextPortForUDP())); - fail("No exception when binding to bad address"); - } catch (SocketException expected) { - } - theSocket.close(); - } - - public void test_bindLjava_net_SocketAddress_address_in_use() throws Exception { - // Address that we have already bound to - int[] ports = Support_PortManager.getNextPortsForUDP(2); - DatagramSocket theSocket1 = new DatagramSocket((SocketAddress) null); - DatagramSocket theSocket2 = new DatagramSocket(ports[0]); - try { - InetSocketAddress theAddress = new InetSocketAddress(InetAddress.getLocalHost(), ports[1]); - theSocket1.bind(theAddress); - theSocket2.bind(theAddress); - fail("No exception binding to address that is not available"); - } catch (SocketException expected) { - } - theSocket1.close(); - theSocket2.close(); - } - - public void test_bindLjava_net_SocketAddress_unsupported_address_type() throws Exception { - class mySocketAddress extends SocketAddress { - public mySocketAddress() { - } - } - - // unsupported SocketAddress subclass - DatagramSocket theSocket = new DatagramSocket((SocketAddress) null); - try { - theSocket.bind(new mySocketAddress()); - fail("No exception when binding using unsupported SocketAddress subclass"); - } catch (IllegalArgumentException expected) { - } - theSocket.close(); - } - - public void test_connectLjava_net_SocketAddress() { - - // validate that we get the PortUnreachable exception if we try to - // send a dgram to a server that is not running and then do a recv - try { - ds = new java.net.DatagramSocket(); - InetAddress inetAddress = InetAddress.getLocalHost(); - int portNumber = Support_PortManager.getNextPortForUDP(); - ds.connect(new InetSocketAddress(inetAddress, portNumber)); - DatagramPacket send = new DatagramPacket(new byte[10], 10); - ds.send(send); - DatagramPacket receive = new DatagramPacket(new byte[20], 20); - ds.setSoTimeout(10000); - ds.receive(receive); - ds.close(); - fail( - "No PortUnreachableException when connected at native level on recv "); - } catch (Exception e) { - assertTrue( - "Wrong exception when trying to connect at native level on recv: " - + e.toString(), - (e instanceof PortUnreachableException)); - } - - try { - ds = new java.net.DatagramSocket(); - InetAddress inetAddress = InetAddress.getLocalHost(); - int portNumber = Support_PortManager.getNextPortForUDP(); - - ds.connect(new InetSocketAddress("asdfasdf", 1)); - ds.close(); - fail("SocketException was not thrown."); - } catch (Exception e) { - assertTrue( - "Wrong exception when trying to connect to unknown host: " - + e.toString(), - (e instanceof SocketException)); - } - - // validate that we can send/receive with datagram sockets connected at - // the native level - DatagramServer server = null; - int[] ports = Support_PortManager.getNextPortsForUDP(3); - int serverPortNumber = ports[0]; - try { - InetAddress localHost = InetAddress.getLocalHost(); - DatagramSocket ds = new DatagramSocket(ports[1]); - DatagramSocket ds2 = new DatagramSocket(ports[2]); - - try { - server = new DatagramServer(serverPortNumber, localHost); - server.start(); - Thread.sleep(1000); - } catch (Exception e) { - fail( - "Failed to set up datagram server for native connected Dgram socket test "); - } - - int port = ds.getLocalPort(); - ds.connect(new InetSocketAddress(localHost, serverPortNumber)); - - byte[] sendBytes = { 'T', 'e', 's', 't', 0 }; - DatagramPacket send = new DatagramPacket(sendBytes, - sendBytes.length); - ds.send(send); - DatagramPacket receive = new DatagramPacket(new byte[20], 20); - ds.setSoTimeout(2000); - ds.receive(receive); - ds.close(); - assertTrue("Wrong size data received: " + receive.getLength(), - receive.getLength() == sendBytes.length); - assertTrue("Wrong data received" - + new String(receive.getData(), 0, receive.getLength()) - + ":" + new String(sendBytes), new String( - receive.getData(), 0, receive.getLength()) - .equals(new String(sendBytes))); - assertTrue("Wrong receiver:" + receive.getAddress() + ":" - + localHost, receive.getAddress().equals(localHost)); - } catch (Exception e) { - fail( - "Unexpected exception when sending data on dgram connected at native level:" - + e.toString()); - } - - if (server != null) { - server.stopServer(); - } - - // validate that we can disconnect - try { - ds = new java.net.DatagramSocket(); - InetAddress inetAddress = InetAddress.getLocalHost(); - int portNumber = Support_PortManager.getNextPortForUDP(); - ds.connect(new InetSocketAddress(inetAddress, portNumber)); - ds.disconnect(); - ds.close(); - } catch (Exception e) { - assertTrue("Unexpected exception when trying to connect at native" - + e.toString(), (e instanceof PortUnreachableException)); - } - - // validate that once connected we cannot send to another address - try { - ds = new java.net.DatagramSocket(); - InetAddress inetAddress = InetAddress.getLocalHost(); - int portNumber = Support_PortManager.getNextPortForUDP(); - ds.connect(new InetSocketAddress(inetAddress, portNumber)); - DatagramPacket send = new DatagramPacket(new byte[10], 10, - inetAddress, portNumber + 1); - ds.send(send); - ds.close(); - fail( - "No Exception when trying to send to a different address on a connected socket "); - } catch (Exception e) { - assertTrue( - "Wrong exception when trying to send to a different address on a connected socket: " - + e.toString(), - (e instanceof IllegalArgumentException)); - } - - // validate that we can connect, then disconnect, then connect then - // send/recv - server = null; - ports = Support_PortManager.getNextPortsForUDP(3); - serverPortNumber = ports[0]; - try { - InetAddress localHost = InetAddress.getLocalHost(); - DatagramSocket ds = new DatagramSocket(ports[1]); - DatagramSocket ds2 = new DatagramSocket(ports[2]); - - try { - server = new DatagramServer(serverPortNumber, localHost); - server.start(); - Thread.sleep(1000); - } catch (Exception e) { - fail( - "Failed to set up datagram server for native connected Dgram socket test "); - } - - int port = ds.getLocalPort(); - ds.connect(new InetSocketAddress(localHost, serverPortNumber + 1)); - ds.disconnect(); - ds.connect(new InetSocketAddress(localHost, serverPortNumber)); - - byte[] sendBytes = { 'T', 'e', 's', 't', 0 }; - DatagramPacket send = new DatagramPacket(sendBytes, - sendBytes.length); - ds.send(send); - DatagramPacket receive = new DatagramPacket(new byte[20], 20); - ds.setSoTimeout(2000); - ds.receive(receive); - ds.close(); - assertTrue( - "connect/disconnect/connect - Wrong size data received: " - + receive.getLength(), - receive.getLength() == sendBytes.length); - assertTrue("connect/disconnect/connect - Wrong data received" - + new String(receive.getData(), 0, receive.getLength()) - + ":" + new String(sendBytes), new String( - receive.getData(), 0, receive.getLength()) - .equals(new String(sendBytes))); - assertTrue("connect/disconnect/connect - Wrong receiver:" - + receive.getAddress() + ":" + localHost, receive - .getAddress().equals(localHost)); - } catch (Exception e) { - fail( - "Unexpected exception when sending data on dgram connected at native level after connect/disconnect/connect:" - + e.toString()); - } - - if (server != null) { - server.stopServer(); - } - - // validate that we can connect/disconnect then send/recv to any address - server = null; - ports = Support_PortManager.getNextPortsForUDP(3); - serverPortNumber = ports[0]; - try { - InetAddress localHost = InetAddress.getLocalHost(); - DatagramSocket ds = new DatagramSocket(ports[1]); - DatagramSocket ds2 = new DatagramSocket(ports[2]); - - try { - server = new DatagramServer(serverPortNumber, localHost); - server.start(); - Thread.sleep(1000); - } catch (Exception e) { - fail( - "Failed to set up datagram server for native connected Dgram socket test "); - } - - int port = ds.getLocalPort(); - ds.connect(new InetSocketAddress(localHost, serverPortNumber + 1)); - ds.disconnect(); - - byte[] sendBytes = { 'T', 'e', 's', 't', 0 }; - DatagramPacket send = new DatagramPacket(sendBytes, - sendBytes.length, localHost, serverPortNumber); - ds.send(send); - DatagramPacket receive = new DatagramPacket(new byte[20], 20); - ds.setSoTimeout(2000); - ds.receive(receive); - ds.close(); - assertTrue("connect/disconnect - Wrong size data received: " - + receive.getLength(), - receive.getLength() == sendBytes.length); - assertTrue("connect/disconnect - Wrong data received" - + new String(receive.getData(), 0, receive.getLength()) - + ":" + new String(sendBytes), new String( - receive.getData(), 0, receive.getLength()) - .equals(new String(sendBytes))); - assertTrue("connect/disconnect - Wrong receiver:" - + receive.getAddress() + ":" + localHost, receive - .getAddress().equals(localHost)); - } catch (Exception e) { - fail( - "Unexpected exception when sending data on dgram connected at native level after connect/disconnect:" - + e.toString()); - } - - if (server != null) { - server.stopServer(); - } - - // validate that we can connect on an allready connected socket and then - // send/recv - server = null; - ports = Support_PortManager.getNextPortsForUDP(3); - serverPortNumber = ports[0]; - try { - InetAddress localHost = InetAddress.getLocalHost(); - DatagramSocket ds = new DatagramSocket(ports[1]); - DatagramSocket ds2 = new DatagramSocket(ports[2]); - - try { - server = new DatagramServer(serverPortNumber, localHost); - server.start(); - Thread.sleep(1000); - } catch (Exception e) { - fail( - "Failed to set up datagram server for native connected Dgram socket test "); - } - - int port = ds.getLocalPort(); - ds.connect(new InetSocketAddress(localHost, serverPortNumber + 1)); - ds.connect(new InetSocketAddress(localHost, serverPortNumber)); - - byte[] sendBytes = { 'T', 'e', 's', 't', 0 }; - DatagramPacket send = new DatagramPacket(sendBytes, - sendBytes.length); - ds.send(send); - DatagramPacket receive = new DatagramPacket(new byte[20], 20); - ds.setSoTimeout(2000); - ds.receive(receive); - ds.close(); - assertTrue("connect/connect - Wrong size data received: " - + receive.getLength(), - receive.getLength() == sendBytes.length); - assertTrue("connect/connect - Wrong data received" - + new String(receive.getData(), 0, receive.getLength()) - + ":" + new String(sendBytes), new String( - receive.getData(), 0, receive.getLength()) - .equals(new String(sendBytes))); - assertTrue("connect/connect - Wrong receiver:" - + receive.getAddress() + ":" + localHost, receive - .getAddress().equals(localHost)); - } catch (Exception e) { - fail( - "Unexpected exception when sending data on dgram connected at native level after connect/connect: " - + e.toString()); - } - - if (server != null) { - server.stopServer(); - } - - // test for when we fail to connect at the native level. It seems to - // fail for the any address so we use this. Now to be compatible we - // don't throw the exception but eat it and then act as if we were - // connected at the Java level. - try { - ds = new java.net.DatagramSocket(); - byte[] addressBytes = { 0, 0, 0, 0 }; - InetAddress inetAddress = InetAddress.getByAddress(addressBytes); - int portNumber = Support_PortManager.getNextPortForUDP(); - InetAddress localHost = InetAddress.getLocalHost(); - ds.connect(new InetSocketAddress(inetAddress, portNumber)); - assertTrue("Is not connected after connect to inaddr any", ds - .isConnected()); - byte[] sendBytes = { 'T', 'e', 's', 't', 0 }; - DatagramPacket send = new DatagramPacket(sendBytes, - sendBytes.length, localHost, portNumber); - ds.send(send); - fail( - "No exception when trying to connect at native level with bad address (exception from send) "); - } catch (Exception e) { - assertTrue( - "Wrong exception when trying to connect at native level with bad address (exception from send): " - + e.toString(), - (e instanceof IllegalArgumentException)); - } - } - - public void test_isBound() { - try { - InetAddress addr = InetAddress.getLocalHost(); - int[] ports = Support_PortManager.getNextPortsForUDP(3); - int port = ports[0]; - - DatagramSocket theSocket = new DatagramSocket(ports[1]); - assertTrue("Socket indicated not bound when it should be (1)", - theSocket.isBound()); - theSocket.close(); - - theSocket = new DatagramSocket(new InetSocketAddress(addr, port)); - assertTrue("Socket indicated not bound when it should be (2)", - theSocket.isBound()); - theSocket.close(); - - theSocket = new DatagramSocket((SocketAddress) null); - assertFalse("Socket indicated bound when it should not be (1)", - theSocket.isBound()); - theSocket.close(); - - // connect causes implicit bind - theSocket = new DatagramSocket((SocketAddress) null); - theSocket.connect(new InetSocketAddress(addr, port)); - assertTrue("Socket indicated not bound when it should be (3)", - theSocket.isBound()); - theSocket.close(); - - // now test when we bind explicitely - InetSocketAddress theLocalAddress = new InetSocketAddress( - InetAddress.getLocalHost(), ports[2]); - theSocket = new DatagramSocket((SocketAddress) null); - assertFalse("Socket indicated bound when it should not be (2)", - theSocket.isBound()); - theSocket.bind(theLocalAddress); - assertTrue("Socket indicated not bound when it should be (4)", - theSocket.isBound()); - theSocket.close(); - assertTrue("Socket indicated not bound when it should be (5)", - theSocket.isBound()); - } catch (Exception e) { - fail("Got exception during isBound tests" + e.toString()); - } - } - - public void test_isConnected() { - try { - InetAddress addr = InetAddress.getLocalHost(); - int[] ports = Support_PortManager.getNextPortsForUDP(4); - int port = ports[0]; - - // base test - DatagramSocket theSocket = new DatagramSocket(ports[1]); - assertFalse("Socket indicated connected when it should not be", - theSocket.isConnected()); - theSocket.connect(new InetSocketAddress(addr, port)); - assertTrue("Socket indicated not connected when it should be", - theSocket.isConnected()); - - // reconnect the socket and make sure we get the right answer - theSocket.connect(new InetSocketAddress(addr, ports[2])); - assertTrue("Socket indicated not connected when it should be", - theSocket.isConnected()); - - // now disconnect the socket and make sure we get the right answer - theSocket.disconnect(); - assertFalse("Socket indicated connected when it should not be", - theSocket.isConnected()); - theSocket.close(); - - // now check behavior when socket is closed when connected - theSocket = new DatagramSocket(ports[3]); - theSocket.connect(new InetSocketAddress(addr, port)); - theSocket.close(); - assertTrue("Socket indicated not connected when it should be", - theSocket.isConnected()); - } catch (Exception e) { - fail("Got exception during isConnected tests" + e.toString()); - } - } - - public void test_getRemoteSocketAddress() { - try { - int[] ports = Support_PortManager.getNextPortsForUDP(3); - int sport = ports[0]; - int portNumber = ports[1]; - DatagramSocket s = new DatagramSocket(new InetSocketAddress( - InetAddress.getLocalHost(), portNumber)); - s.connect(new InetSocketAddress(InetAddress.getLocalHost(), sport)); - assertTrue("Returned incorrect InetSocketAddress(1):" - + s.getLocalSocketAddress().toString(), s - .getRemoteSocketAddress().equals( - new InetSocketAddress(InetAddress.getLocalHost(), - sport))); - s.close(); - - // now create one that is not connected and validate that we get the - // right answer - DatagramSocket theSocket = new DatagramSocket((SocketAddress) null); - portNumber = ports[2]; - theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), - portNumber)); - assertNull( - "Returned incorrect InetSocketAddress -unconnected socket:" - + "Expected: NULL", theSocket - .getRemoteSocketAddress()); - - // now connect and validate we get the right answer - theSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(), - sport)); - assertTrue("Returned incorrect InetSocketAddress(2):" - + theSocket.getRemoteSocketAddress().toString(), theSocket - .getRemoteSocketAddress().equals( - new InetSocketAddress(InetAddress.getLocalHost(), - sport))); - theSocket.close(); - - } catch (Exception e) { - fail("Exception during getRemoteSocketAddress test: " + e); - } - } - - public void test_setReuseAddressZ() throws Exception { - // test case were we set it to false - DatagramSocket theSocket1 = null; - DatagramSocket theSocket2 = null; - try { - InetSocketAddress theAddress = new InetSocketAddress( - InetAddress.getLocalHost(), Support_PortManager - .getNextPortForUDP()); - theSocket1 = new DatagramSocket((SocketAddress) null); - theSocket2 = new DatagramSocket((SocketAddress) null); - theSocket1.setReuseAddress(false); - theSocket2.setReuseAddress(false); - theSocket1.bind(theAddress); - theSocket2.bind(theAddress); - fail( - "No exception when trying to connect to do duplicate socket bind with re-useaddr set to false"); - } catch (BindException e) { - - } - if (theSocket1 != null) - theSocket1.close(); - if (theSocket2 != null) - theSocket2.close(); - - // test case were we set it to true - try { - InetSocketAddress theAddress = new InetSocketAddress( - InetAddress.getLocalHost(), Support_PortManager - .getNextPortForUDP()); - theSocket1 = new DatagramSocket((SocketAddress) null); - theSocket2 = new DatagramSocket((SocketAddress) null); - theSocket1.setReuseAddress(true); - theSocket2.setReuseAddress(true); - theSocket1.bind(theAddress); - theSocket2.bind(theAddress); - } catch (Exception e) { - fail( - "unexpected exception when trying to connect to do duplicate socket bind with re-useaddr set to true"); - } - if (theSocket1 != null) - theSocket1.close(); - if (theSocket2 != null) - theSocket2.close(); - - // test the default case which we expect to be the same on all - // platforms - try { - InetSocketAddress theAddress = new InetSocketAddress( - InetAddress.getLocalHost(), Support_PortManager - .getNextPortForUDP()); - theSocket1 = new DatagramSocket((SocketAddress) null); - theSocket2 = new DatagramSocket((SocketAddress) null); - theSocket1.bind(theAddress); - theSocket2.bind(theAddress); - fail( - "No exception when trying to connect to do duplicate socket bind with re-useaddr left as default"); - } catch (BindException e) { - - } - if (theSocket1 != null) - theSocket1.close(); - if (theSocket2 != null) - theSocket2.close(); - - try { - theSocket1.setReuseAddress(true); - fail("SocketException was not thrown."); - } catch(SocketException se) { - //expected - } - } - - public void test_getReuseAddress() throws Exception { - DatagramSocket theSocket = new DatagramSocket(); - theSocket.setReuseAddress(true); - assertTrue("getReuseAddress false when it should be true", - theSocket.getReuseAddress()); - theSocket.setReuseAddress(false); - assertFalse("getReuseAddress true when it should be false", - theSocket.getReuseAddress()); - theSocket.close(); - try { - theSocket.getReuseAddress(); - fail("SocketException was not thrown."); - } catch(SocketException se) { - //expected - } - } - - public void test_setBroadcastZ() throws Exception { - int[] ports = Support_PortManager.getNextPortsForUDP(3); - DatagramSocket theSocket = new DatagramSocket(ports[0]); - theSocket.setBroadcast(false); - byte theBytes[] = { -1, -1, -1, -1 }; - - // validate we cannot connect to the broadcast address when - // setBroadcast is false - try { - theSocket.connect(new InetSocketAddress(InetAddress - .getByAddress(theBytes), ports[1])); - assertFalse( - "No exception when connecting to broadcast address with setBroadcast(false)", - theSocket.getBroadcast()); - } catch (SocketException ex) { - //expected - } - - // now validate that we can connect to the broadcast address when - // setBroadcast is true - theSocket.setBroadcast(true); - theSocket.connect(new InetSocketAddress(InetAddress - .getByAddress(theBytes), ports[2])); - - theSocket.close(); - try { - theSocket.setBroadcast(false); - fail("SocketException was not thrown."); - } catch(SocketException se) { - //expected - } - } - - public void test_getBroadcast() throws Exception { - DatagramSocket theSocket = new DatagramSocket(); - theSocket.setBroadcast(true); - assertTrue("getBroadcast false when it should be true", theSocket - .getBroadcast()); - theSocket.setBroadcast(false); - assertFalse("getBroadcast true when it should be False", theSocket - .getBroadcast()); - theSocket.close(); - try { - theSocket.getBroadcast(); - fail("SocketException was not thrown."); - } catch(SocketException se) { - //expected - } - } - - public void test_setTrafficClassI() throws Exception { - int IPTOS_LOWCOST = 0x2; - int IPTOS_RELIABILTY = 0x4; - int IPTOS_THROUGHPUT = 0x8; - int IPTOS_LOWDELAY = 0x10; - int[] ports = Support_PortManager.getNextPortsForUDP(2); - - new InetSocketAddress(InetAddress.getLocalHost(), - ports[0]); - DatagramSocket theSocket = new DatagramSocket(ports[1]); - - // validate that value set must be between 0 and 255 - try { - theSocket.setTrafficClass(256); - fail("No exception when traffic class set to 256"); - } catch (IllegalArgumentException e) { - } - - try { - theSocket.setTrafficClass(-1); - fail("No exception when traffic class set to -1"); - } catch (IllegalArgumentException e) { - } - - // now validate that we can set it to some good values - theSocket.setTrafficClass(IPTOS_LOWCOST); - theSocket.setTrafficClass(IPTOS_THROUGHPUT); - - theSocket.close(); - try { - theSocket.setTrafficClass(1); - fail("SocketException was not thrown."); - } catch(SocketException se) { - //expected - } - } - - public void test_getTrafficClass() throws Exception { - int IPTOS_LOWCOST = 0x2; - int IPTOS_RELIABILTY = 0x4; - int IPTOS_THROUGHPUT = 0x8; - int IPTOS_LOWDELAY = 0x10; - int[] ports = Support_PortManager.getNextPortsForUDP(2); - - new InetSocketAddress(InetAddress.getLocalHost(), - ports[0]); - DatagramSocket theSocket = new DatagramSocket(ports[1]); - - /* - * we cannot actually check that the values are set as if a platform - * does not support the option then it may come back unset even - * though we set it so just get the value to make sure we can get it - */ - int trafficClass = theSocket.getTrafficClass(); - - theSocket.close(); - try { - theSocket.getTrafficClass(); - fail("SocketException was not thrown."); - } catch(SocketException se) { - //expected - } - } - - public void test_isClosed() { - try { - DatagramSocket theSocket = new DatagramSocket(); - - // validate isClosed returns expected values - assertFalse("Socket should indicate it is not closed(1):", - theSocket.isClosed()); - theSocket.close(); - assertTrue("Socket should indicate it is not closed(1):", theSocket - .isClosed()); - - InetSocketAddress theAddress = new InetSocketAddress(InetAddress - .getLocalHost(), Support_PortManager.getNextPortForUDP()); - theSocket = new DatagramSocket(theAddress); - assertFalse("Socket should indicate it is not closed(2):", - theSocket.isClosed()); - theSocket.close(); - assertTrue("Socket should indicate it is not closed(2):", theSocket - .isClosed()); - } catch (Exception e) { - fail("Got exception during isClosed tests" + e.toString()); - } - } - - public void test_getChannel() throws Exception { - assertNull(new DatagramSocket().getChannel()); - - int portNumber = Support_PortManager.getNextPortForUDP(); - DatagramSocket ds = null; - try { - InetAddress ia = InetAddress - .getByName(Support_Configuration.IPv6GlobalAddressJcl4); - ds = new DatagramSocket(); - assertNull(ds.getChannel()); - ds.connect(ia, portNumber); - assertNull(ds.getChannel()); - } catch (SocketException e) { - fail("SocketException was thrown."); - } finally { - ds.disconnect(); - ds.close(); - } - portNumber = Support_PortManager.getNextPortForUDP(); - SocketAddress address = new InetSocketAddress(portNumber); - DatagramChannel channel = DatagramChannel.open(); - DatagramSocket socket = channel.socket(); - assertEquals(channel, socket.getChannel()); - socket.close(); - } - - class TestDatagramSocketImplFactory implements DatagramSocketImplFactory { - public DatagramSocketImpl createDatagramSocketImpl() { - return new TestDatagramSocketImpl(); - } - } - - class TestDatagramSocketImpl extends DatagramSocketImpl { - - @Override - protected void bind(int arg0, InetAddress arg1) throws SocketException { - // TODO Auto-generated method stub - - } - - @Override - protected void close() { - // TODO Auto-generated method stub - - } - - @Override - protected void create() throws SocketException { - // TODO Auto-generated method stub - - } - - @Override - protected byte getTTL() throws IOException { - // TODO Auto-generated method stub - return 0; - } - - @Override - protected int getTimeToLive() throws IOException { - // TODO Auto-generated method stub - return 0; - } - - @Override - protected void join(InetAddress arg0) throws IOException { - // TODO Auto-generated method stub - - } - - @Override - protected void joinGroup(SocketAddress arg0, NetworkInterface arg1) throws IOException { - // TODO Auto-generated method stub - - } - - @Override - protected void leave(InetAddress arg0) throws IOException { - // TODO Auto-generated method stub - - } - - @Override - protected void leaveGroup(SocketAddress arg0, NetworkInterface arg1) throws IOException { - // TODO Auto-generated method stub - - } - - @Override - protected int peek(InetAddress arg0) throws IOException { - // TODO Auto-generated method stub - return 0; - } - - @Override - protected int peekData(DatagramPacket arg0) throws IOException { - // TODO Auto-generated method stub - return 0; - } - - @Override - protected void receive(DatagramPacket arg0) throws IOException { - // TODO Auto-generated method stub - - } - - @Override - protected void send(DatagramPacket arg0) throws IOException { - // TODO Auto-generated method stub - - } - - @Override - protected void setTTL(byte arg0) throws IOException { - // TODO Auto-generated method stub - - } - - @Override - protected void setTimeToLive(int arg0) throws IOException { - // TODO Auto-generated method stub - - } - - public Object getOption(int arg0) throws SocketException { - // TODO Auto-generated method stub - return null; - } - - public void setOption(int arg0, Object arg1) throws SocketException { - // TODO Auto-generated method stub - - } - - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - retval = "Bogus retval"; - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - try { - ds.close(); - sds.close(); - } catch (Exception e) { - } - } - - protected void receive_oversize_java_net_DatagramPacket() throws Exception { - final int[] ports = Support_PortManager.getNextPortsForUDP(2); - final int portNumber = ports[0]; - - class TestDGRcvOver implements Runnable { - public void run() { - InetAddress localHost = null; - try { - localHost = InetAddress.getLocalHost(); - Thread.sleep(1000); - DatagramSocket sds = new DatagramSocket(ports[1]); - DatagramPacket rdp = new DatagramPacket("0123456789" - .getBytes(), 10, localHost, portNumber); - sds.send(rdp); - sds.close(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - } - - try { - new Thread(new TestDGRcvOver(), "DGSenderOver").start(); - ds = new java.net.DatagramSocket(portNumber); - ds.setSoTimeout(6000); - byte rbuf[] = new byte[5]; - DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length); - ; - ds.receive(rdp); - ds.close(); - assertTrue("Send/Receive oversize failed to return correct data: " - + new String(rbuf, 0, 5), new String(rbuf, 0, 5) - .equals("01234")); - } finally { - ds.close(); - } - } -} diff --git a/luni/src/test/java/libcore/java/net/OldFileNameMapTest.java b/luni/src/test/java/libcore/java/net/OldFileNameMapTest.java index de9caa9..4fe3ef4 100644 --- a/luni/src/test/java/libcore/java/net/OldFileNameMapTest.java +++ b/luni/src/test/java/libcore/java/net/OldFileNameMapTest.java @@ -22,19 +22,11 @@ import java.net.FileNameMap; import java.net.URLConnection; public class OldFileNameMapTest extends TestCase { - - public void test_getContentTypeFor() { - String [] files = {"text", "txt", "htm", "html"}; - - String [] mimeTypes = {"text/plain", "text/plain", - "text/html", "text/html"}; - - FileNameMap fileNameMap = URLConnection.getFileNameMap(); - - for(int i = 0; i < files.length; i++) { - String mimeType = fileNameMap.getContentTypeFor("test." + files[i]); - assertEquals("getContentTypeFor returns incorrect MIME type for " + - files[i], mimeTypes[i], mimeType); - } - } + public void test_getContentTypeFor() { + FileNameMap map = URLConnection.getFileNameMap(); + assertEquals("text/plain", map.getContentTypeFor("test.text")); + assertEquals("text/plain", map.getContentTypeFor("test.txt")); + assertEquals("text/html", map.getContentTypeFor("test.htm")); + assertEquals("text/html", map.getContentTypeFor("test.html")); + } } diff --git a/luni/src/test/java/libcore/java/net/OldSocketTest.java b/luni/src/test/java/libcore/java/net/OldSocketTest.java index 033a7bf..7973965 100644 --- a/luni/src/test/java/libcore/java/net/OldSocketTest.java +++ b/luni/src/test/java/libcore/java/net/OldSocketTest.java @@ -95,10 +95,9 @@ public class OldSocketTest extends OldSocketTestCase { } try { - new Socket("unknown.host", 0); + new Socket("unknown.host.google.com", 0); fail("UnknownHostException was not thrown."); - } catch(UnknownHostException uhe) { - //expected + } catch (UnknownHostException expected) { } Socket socket = null; try { @@ -120,9 +119,10 @@ public class OldSocketTest extends OldSocketTestCase { } public void test_ConstructorLjava_lang_StringILjava_net_InetAddressI2() throws IOException { - Socket s1 = new Socket("www.google.com", 80, null, 0); + int sport = startServer("Cons String,I,InetAddress,I"); + Socket s1 = new Socket(InetAddress.getLocalHost(), sport, null, 0); try { - Socket s2 = new Socket("www.google.com", 80, null, s1.getLocalPort()); + Socket s2 = new Socket(InetAddress.getLocalHost(), sport, null, s1.getLocalPort()); try { s2.close(); } catch (IOException ignored) { @@ -1251,6 +1251,12 @@ public class OldSocketTest extends OldSocketTestCase { theSocket.connect(nonReachableAddress, 200); theSocket.close(); fail("No interrupted exception when connecting to address nobody listening on with short timeout 200: "); + } catch (ConnectException ce) { + // some networks will quickly reset the TCP connection attempt to this fake IP + assertTrue( + "Wrong exception when connecting to address nobody listening on with short timeout 200: " + + ce.toString(), + (ce.getMessage() != null && ce.getMessage().contains("ECONNREFUSED"))); } catch (Exception e) { assertTrue( "Wrong exception when connecting to address nobody listening on with short timeout 200: " @@ -1266,6 +1272,12 @@ public class OldSocketTest extends OldSocketTestCase { theSocket.connect(nonReachableAddress, 40); theSocket.close(); fail("No interrupted exception when connecting to address nobody listening on with short timeout 40: "); + } catch (ConnectException ce) { + // some networks will quickly reset the TCP connection attempt to this fake IP + assertTrue( + "Wrong exception when connecting to address nobody listening on with short timeout 40: " + + ce.toString(), + (ce.getMessage() != null && ce.getMessage().contains("ECONNREFUSED"))); } catch (Exception e) { assertTrue( "Wrong exception when connecting to address nobody listening on with short timeout 40: " diff --git a/luni/src/test/java/libcore/java/net/OldURLClassLoaderTest.java b/luni/src/test/java/libcore/java/net/OldURLClassLoaderTest.java index 3a5608c..c076f1d 100644 --- a/luni/src/test/java/libcore/java/net/OldURLClassLoaderTest.java +++ b/luni/src/test/java/libcore/java/net/OldURLClassLoaderTest.java @@ -17,7 +17,6 @@ package libcore.java.net; -import dalvik.annotation.SideEffect; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -26,15 +25,11 @@ import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.security.CodeSource; -import java.security.Permission; import java.security.PermissionCollection; -import java.security.cert.Certificate; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.jar.Manifest; -import org.apache.harmony.security.tests.support.TestCertUtils; -import tests.support.Support_Configuration; import tests.support.Support_TestWebData; import tests.support.Support_TestWebServer; import tests.support.resource.Support_Resources; @@ -42,15 +37,6 @@ import tests.support.resource.Support_Resources; public class OldURLClassLoaderTest extends junit.framework.TestCase { URLClassLoader ucl; - SecurityManager sm = new SecurityManager() { - - public void checkPermission(Permission perm) { - } - - public void checkCreateClassLoader() { - throw new SecurityException(); - } - }; /** * java.net.URLClassLoader#URLClassLoader(java.net.URL[]) @@ -58,8 +44,8 @@ public class OldURLClassLoaderTest extends junit.framework.TestCase { public void test_Constructor$Ljava_net_URL() throws MalformedURLException { URL[] u = new URL[0]; ucl = new URLClassLoader(u); - assertTrue("Failed to set parent", ucl != null - && ucl.getParent() == URLClassLoader.getSystemClassLoader()); + assertTrue("Failed to set parent", + ucl.getParent() == URLClassLoader.getSystemClassLoader()); URL [] urls = {new URL("http://foo.com/foo"), @@ -87,7 +73,6 @@ public class OldURLClassLoaderTest extends junit.framework.TestCase { * java.net.URLClassLoader#findResources(java.lang.String) */ public void test_findResourcesLjava_lang_String() throws Exception { - Enumeration<URL> res = null; String[] resValues = { "This is a test resource file.", "This is a resource from a subdir"}; @@ -115,7 +100,7 @@ public class OldURLClassLoaderTest extends junit.framework.TestCase { urls[1] = new URL("file://" + subDir.getAbsolutePath() + "/"); ucl = new URLClassLoader(urls); - res = ucl.findResources("test0"); + Enumeration<URL> res = ucl.findResources("test0"); assertNotNull("Failed to locate resources", res); int i = 0; @@ -207,7 +192,7 @@ public class OldURLClassLoaderTest extends junit.framework.TestCase { } } - @SideEffect("Support_TestWebServer requires isolation.") + // SideEffect: Support_TestWebServer requires isolation. public void test_findResourceLjava_lang_String() throws Exception { File tmp = File.createTempFile("test", ".txt"); @@ -232,7 +217,7 @@ public class OldURLClassLoaderTest extends junit.framework.TestCase { /** * Regression for Harmony-2237 */ - @SideEffect("Support_TestWebServer requires isolation.") + // SideEffect: Support_TestWebServer requires isolation. public void test_findResource_String() throws Exception { File tempFile1 = File.createTempFile("textFile", ".txt"); tempFile1.createNewFile(); @@ -250,19 +235,17 @@ public class OldURLClassLoaderTest extends junit.framework.TestCase { "/tests/resources/hyts_patch.jar"); Support_Resources.copyLocalFileto(tempFile2, is); String tempPath2 = tempFile2.getAbsolutePath(); - String tempPath3 = "http://localhost:" + port + "/"; URLClassLoader urlLoader = getURLClassLoader(tempPath1, tempPath2); - assertNull("Found inexistant resource", - urlLoader.findResource("XXX")); + assertNull("Found nonexistent resource", urlLoader.findResource("XXX")); assertNotNull("Couldn't find resource from directory", urlLoader.findResource(tempFile1.getName())); - assertNotNull("Couldn't find resource from jar", - urlLoader.findResource("Blah.txt")); + assertNotNull("Couldn't find resource from jar", urlLoader.findResource("Blah.txt")); + + String tempPath3 = "http://localhost:" + port + "/"; urlLoader = getURLClassLoader(tempPath1, tempPath2, tempPath3); - assertNotNull("Couldn't find resource from web", - urlLoader.findResource("test1")); - assertNull("Found inexistant resource from web", - urlLoader.findResource("test3")); + assertNotNull("Couldn't find resource from web", urlLoader.findResource("test1")); + // Attempt to find a resource using a URL that will produce a 404. + assertNull("Found nonexistent resource from web", urlLoader.findResource("test9999")); } finally { server.close(); } diff --git a/luni/src/test/java/libcore/java/net/ServerSocketTest.java b/luni/src/test/java/libcore/java/net/ServerSocketTest.java index fe9d423..d82e934 100644 --- a/luni/src/test/java/libcore/java/net/ServerSocketTest.java +++ b/luni/src/test/java/libcore/java/net/ServerSocketTest.java @@ -17,6 +17,8 @@ package libcore.java.net; import java.io.IOException; +import java.net.Inet4Address; +import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; @@ -43,4 +45,34 @@ public class ServerSocketTest extends junit.framework.TestCase { t.join(); assertEquals(0, result[0].getSoTimeout()); } + + public void testInitialState() throws Exception { + ServerSocket ss = new ServerSocket(); + try { + assertFalse(ss.isBound()); + assertFalse(ss.isClosed()); + assertEquals(-1, ss.getLocalPort()); + assertNull(ss.getLocalSocketAddress()); + assertNull(ss.getInetAddress()); + assertTrue(ss.getReuseAddress()); + assertNull(ss.getChannel()); + } finally { + ss.close(); + } + } + + public void testStateAfterClose() throws Exception { + ServerSocket ss = new ServerSocket(); + ss.bind(new InetSocketAddress(Inet4Address.getLocalHost(), 0)); + InetSocketAddress boundAddress = (InetSocketAddress) ss.getLocalSocketAddress(); + ss.close(); + + assertTrue(ss.isBound()); + assertTrue(ss.isClosed()); + assertEquals(boundAddress.getAddress(), ss.getInetAddress()); + assertEquals(boundAddress.getPort(), ss.getLocalPort()); + + InetSocketAddress localAddressAfterClose = (InetSocketAddress) ss.getLocalSocketAddress(); + assertEquals(boundAddress, localAddressAfterClose); + } } diff --git a/luni/src/test/java/libcore/java/net/SocketTest.java b/luni/src/test/java/libcore/java/net/SocketTest.java index 42b7250..fb09be0 100644 --- a/luni/src/test/java/libcore/java/net/SocketTest.java +++ b/luni/src/test/java/libcore/java/net/SocketTest.java @@ -20,6 +20,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ConnectException; +import java.net.Inet4Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; @@ -109,10 +110,12 @@ public class SocketTest extends junit.framework.TestCase { in.socket().setTcpNoDelay(false); } + InetSocketAddress listenAddress = (InetSocketAddress) in.socket().getLocalSocketAddress(); InetSocketAddress outRemoteAddress = (InetSocketAddress) out.socket().getRemoteSocketAddress(); InetSocketAddress outLocalAddress = (InetSocketAddress) out.socket().getLocalSocketAddress(); InetSocketAddress inLocalAddress = (InetSocketAddress) in.socket().getLocalSocketAddress(); InetSocketAddress inRemoteAddress = (InetSocketAddress) in.socket().getRemoteSocketAddress(); + System.err.println("listenAddress: " + listenAddr); System.err.println("inLocalAddress: " + inLocalAddress); System.err.println("inRemoteAddress: " + inRemoteAddress); System.err.println("outLocalAddress: " + outLocalAddress); @@ -127,14 +130,42 @@ public class SocketTest extends junit.framework.TestCase { assertEquals(outLocalAddress.getAddress(), ss.getInetAddress()); assertEquals(outRemoteAddress.getAddress(), ss.getInetAddress()); + assertFalse(ssc.socket().isClosed()); + assertTrue(ssc.socket().isBound()); + assertTrue(in.isConnected()); + assertTrue(in.socket().isConnected()); + assertTrue(out.socket().isConnected()); + assertTrue(out.isConnected()); + in.close(); out.close(); ssc.close(); + assertTrue(ssc.socket().isClosed()); + assertTrue(ssc.socket().isBound()); + assertFalse(in.isConnected()); + assertFalse(in.socket().isConnected()); + assertFalse(out.socket().isConnected()); + assertFalse(out.isConnected()); + assertNull(in.socket().getRemoteSocketAddress()); assertNull(out.socket().getRemoteSocketAddress()); - assertEquals(in.socket().getLocalSocketAddress(), ss.getLocalSocketAddress()); + // As per docs and RI - server socket local address methods continue to return the bind() + // addresses even after close(). + assertEquals(listenAddress, ssc.socket().getLocalSocketAddress()); + + // As per docs and RI - socket local address methods return the wildcard address before + // bind() and after close(), but the port will be the same as it was before close(). + InetSocketAddress inLocalAddressAfterClose = + (InetSocketAddress) in.socket().getLocalSocketAddress(); + assertTrue(inLocalAddressAfterClose.getAddress().isAnyLocalAddress()); + assertEquals(inLocalAddress.getPort(), inLocalAddressAfterClose.getPort()); + + InetSocketAddress outLocalAddressAfterClose = + (InetSocketAddress) out.socket().getLocalSocketAddress(); + assertTrue(outLocalAddressAfterClose.getAddress().isAnyLocalAddress()); + assertEquals(outLocalAddress.getPort(), outLocalAddressAfterClose.getPort()); } // SocketOptions.setOption has weird behavior for setSoLinger/SO_LINGER. @@ -286,6 +317,42 @@ public class SocketTest extends junit.framework.TestCase { serverSocket.close(); } + public void testInitialState() throws Exception { + Socket s = new Socket(); + try { + assertFalse(s.isBound()); + assertFalse(s.isClosed()); + assertFalse(s.isConnected()); + assertEquals(-1, s.getLocalPort()); + assertTrue(s.getLocalAddress().isAnyLocalAddress()); + assertNull(s.getLocalSocketAddress()); + assertNull(s.getInetAddress()); + assertEquals(0, s.getPort()); + assertNull(s.getRemoteSocketAddress()); + assertFalse(s.getReuseAddress()); + assertNull(s.getChannel()); + } finally { + s.close(); + } + } + + public void testStateAfterClose() throws Exception { + Socket s = new Socket(); + s.bind(new InetSocketAddress(Inet4Address.getLocalHost(), 0)); + InetSocketAddress boundAddress = (InetSocketAddress) s.getLocalSocketAddress(); + s.close(); + + assertTrue(s.isBound()); + assertTrue(s.isClosed()); + assertFalse(s.isConnected()); + assertTrue(s.getLocalAddress().isAnyLocalAddress()); + assertEquals(boundAddress.getPort(), s.getLocalPort()); + + InetSocketAddress localAddressAfterClose = (InetSocketAddress) s.getLocalSocketAddress(); + assertTrue(localAddressAfterClose.getAddress().isAnyLocalAddress()); + assertEquals(boundAddress.getPort(), localAddressAfterClose.getPort()); + } + static class MockServer { private ExecutorService executor; private ServerSocket serverSocket; diff --git a/luni/src/test/java/libcore/java/net/URITest.java b/luni/src/test/java/libcore/java/net/URITest.java index 04a7d2e..7f4c086 100644 --- a/luni/src/test/java/libcore/java/net/URITest.java +++ b/luni/src/test/java/libcore/java/net/URITest.java @@ -16,9 +16,9 @@ package libcore.java.net; +import junit.framework.TestCase; import java.net.URI; import java.net.URISyntaxException; -import junit.framework.TestCase; import libcore.util.SerializationTester; public final class URITest extends TestCase { @@ -57,6 +57,24 @@ public final class URITest extends TestCase { .equals(new URI("http://localhost/foo?bar=baz#QUUX"))); } + public void testEqualsEscaping() throws Exception { + // Case insensitive when comparing escaped values, but not when + // comparing unescaped values. + assertEquals(new URI("http://localhost/foo?bar=fooobar%E0%AE%A8%E0bar"), + new URI("http://localhost/foo?bar=fooobar%E0%AE%a8%e0bar")); + assertFalse(new URI("http://localhost/foo?bar=fooobar%E0%AE%A8%E0bar").equals( + new URI("http://localhost/foo?bar=FoooBar%E0%AE%a8%e0bar"))); + assertFalse(new URI("http://localhost/foo?bar=fooobar%E0%AE%A8%E0bar").equals( + new URI("http://localhost/foo?bar=fooobar%E0%AE%a8%e0BaR"))); + + // Last byte replaced by an unescaped value. + assertFalse(new URI("http://localhost/foo?bar=%E0%AE%A8%E0").equals( + new URI("http://localhost/foo?bar=%E0%AE%a8xxx"))); + // Missing byte. + assertFalse(new URI("http://localhost/foo?bar=%E0%AE%A8%E0").equals( + new URI("http://localhost/foo?bar=%E0%AE%a8"))); + } + public void testFileEqualsWithEmptyHost() throws Exception { assertEquals(new URI("file", "", "/a/", null), new URI("file:/a/")); assertEquals(new URI("file", null, "/a/", null), new URI("file:/a/")); @@ -511,7 +529,7 @@ public final class URITest extends TestCase { assertEquals("b/c", a.relativize(b).toString()); // RI assumes a directory } - public void testParseServerAuthorityInvalidAuthority() throws Exception { + public void testParseServerAuthorityInvalidPortMinus() throws Exception { URI uri = new URI("http://host:-2/"); assertEquals("host:-2", uri.getAuthority()); assertNull(uri.getHost()); @@ -523,6 +541,30 @@ public final class URITest extends TestCase { } } + public void testParseServerAuthorityInvalidPortPlus() throws Exception { + URI uri = new URI("http://host:+2/"); + assertEquals("host:+2", uri.getAuthority()); + assertNull(uri.getHost()); + assertEquals(-1, uri.getPort()); + try { + uri.parseServerAuthority(); + fail(); + } catch (URISyntaxException expected) { + } + } + + public void testParseServerAuthorityInvalidPortNonASCII() throws Exception { + URI uri = new URI("http://host:١٢٣/"); // 123 in arabic + assertEquals("host:١٢٣", uri.getAuthority()); + assertNull(uri.getHost()); + assertEquals(-1, uri.getPort()); + try { + uri.parseServerAuthority(); + fail(); + } catch (URISyntaxException expected) { + } + } + public void testParseServerAuthorityOmittedAuthority() throws Exception { URI uri = new URI("http:file"); uri.parseServerAuthority(); // does nothing! diff --git a/luni/src/test/java/libcore/java/net/URLConnectionTest.java b/luni/src/test/java/libcore/java/net/URLConnectionTest.java index 4ed7f0e..f438d1b 100644 --- a/luni/src/test/java/libcore/java/net/URLConnectionTest.java +++ b/luni/src/test/java/libcore/java/net/URLConnectionTest.java @@ -21,9 +21,7 @@ import com.google.mockwebserver.MockResponse; import com.google.mockwebserver.MockWebServer; import com.google.mockwebserver.RecordedRequest; import com.google.mockwebserver.SocketPolicy; -import dalvik.system.CloseGuard; import java.io.ByteArrayOutputStream; -import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -31,7 +29,6 @@ import java.io.OutputStream; import java.net.Authenticator; import java.net.CacheRequest; import java.net.CacheResponse; -import java.net.ConnectException; import java.net.HttpRetryException; import java.net.HttpURLConnection; import java.net.InetAddress; @@ -71,20 +68,20 @@ import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; -import junit.framework.TestCase; -import libcore.java.lang.ref.FinalizationTester; import libcore.java.security.StandardNames; import libcore.java.security.TestKeyStore; +import libcore.java.util.AbstractResourceLeakageDetectorTestCase; import libcore.javax.net.ssl.TestSSLContext; import tests.net.StuckServer; -import static com.google.mockwebserver.SocketPolicy.DISCONNECT_AFTER_READING_REQUEST; import static com.google.mockwebserver.SocketPolicy.DISCONNECT_AT_END; import static com.google.mockwebserver.SocketPolicy.DISCONNECT_AT_START; +import static com.google.mockwebserver.SocketPolicy.FAIL_HANDSHAKE; import static com.google.mockwebserver.SocketPolicy.SHUTDOWN_INPUT_AT_END; import static com.google.mockwebserver.SocketPolicy.SHUTDOWN_OUTPUT_AT_END; -public final class URLConnectionTest extends TestCase { +public final class URLConnectionTest extends AbstractResourceLeakageDetectorTestCase { + private MockWebServer server; private HttpResponseCache cache; private String hostName; @@ -105,8 +102,10 @@ public final class URLConnectionTest extends TestCase { System.clearProperty("https.proxyHost"); System.clearProperty("https.proxyPort"); server.shutdown(); + server = null; if (cache != null) { cache.delete(); + cache = null; } super.tearDown(); } @@ -325,6 +324,12 @@ public final class URLConnectionTest extends TestCase { public void testServerShutdownOutput() throws Exception { // This test causes MockWebServer to log a "connection failed" stack trace + + // Setting the server workerThreads to 1 ensures the responses are generated in the order + // the requests are accepted by the server. Without this the second and third requests made + // by the client (the request for "/b" and the retry for "/b" when the bad socket is + // detected) can be handled by the server out of order leading to test failure. + server.setWorkerThreads(1); server.enqueue(new MockResponse() .setBody("Output shutdown after this response") .setSocketPolicy(SHUTDOWN_OUTPUT_AT_END)); @@ -433,7 +438,7 @@ public final class URLConnectionTest extends TestCase { RecordedRequest request = server.takeRequest(); assertEquals("GET /foo HTTP/1.1", request.getRequestLine()); - assertEquals("TLSv1", request.getSslProtocol()); + assertEquals("TLSv1.2", request.getSslProtocol()); } public void testConnectViaHttpsReusingConnections() throws IOException, InterruptedException { @@ -801,47 +806,17 @@ public final class URLConnectionTest extends TestCase { } public void testDisconnectAfterOnlyResponseCodeCausesNoCloseGuardWarning() throws IOException { - CloseGuardGuard guard = new CloseGuardGuard(); - try { - server.enqueue(new MockResponse() - .setBody(gzip("ABCABCABC".getBytes("UTF-8"))) - .addHeader("Content-Encoding: gzip")); - server.play(); + server.enqueue(new MockResponse() + .setBody(gzip("ABCABCABC".getBytes("UTF-8"))) + .addHeader("Content-Encoding: gzip")); + server.play(); - HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection(); + HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection(); + try { assertEquals(200, connection.getResponseCode()); - connection.disconnect(); - connection = null; - assertFalse(guard.wasCloseGuardCalled()); } finally { - guard.close(); - } - } - - public static class CloseGuardGuard implements Closeable, CloseGuard.Reporter { - private final CloseGuard.Reporter oldReporter = CloseGuard.getReporter(); - - private AtomicBoolean closeGuardCalled = new AtomicBoolean(); - - public CloseGuardGuard() { - CloseGuard.setReporter(this); - } - - @Override public void report(String message, Throwable allocationSite) { - oldReporter.report(message, allocationSite); - closeGuardCalled.set(true); - } - - public boolean wasCloseGuardCalled() { - FinalizationTester.induceFinalization(); - close(); - return closeGuardCalled.get(); - } - - @Override public void close() { - CloseGuard.setReporter(oldReporter); + connection.disconnect(); } - } public void testDefaultRequestProperty() throws Exception { @@ -990,6 +965,7 @@ public final class URLConnectionTest extends TestCase { RecordedRequest request = server.takeRequest(); assertContains(request.getHeaders(), "Accept-Encoding: gzip"); + assertEquals("gzip", connection.getContentEncoding()); } public void testGzipAndConnectionReuseWithFixedLength() throws Exception { @@ -1065,25 +1041,37 @@ public final class URLConnectionTest extends TestCase { } /** - * Obnoxiously test that the chunk sizes transmitted exactly equal the - * requested data+chunk header size. Although setChunkedStreamingMode() - * isn't specific about whether the size applies to the data or the - * complete chunk, the RI interprets it as a complete chunk. + * Test that request body chunking works. This test has been relaxed from treating + * the {@link java.net.HttpURLConnection#setChunkedStreamingMode(int)} + * chunk length as being fixed because OkHttp no longer guarantees + * the fixed chunk size. Instead, we check that chunking takes place + * and we force the chunk size with flushes. */ public void testSetChunkedStreamingMode() throws IOException, InterruptedException { server.enqueue(new MockResponse()); server.play(); HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection(); - urlConnection.setChunkedStreamingMode(8); + // Later releases of Android ignore the value for chunkLength if it is > 0 and default to + // a fixed chunkLength. During the change-over period while the chunkLength indicates the + // chunk buffer size (inc. header) the chunkLength has to be >= 8. This enables the flush() + // to dictate the size of the chunks. + urlConnection.setChunkedStreamingMode(50 /* chunkLength */); urlConnection.setDoOutput(true); OutputStream outputStream = urlConnection.getOutputStream(); - outputStream.write("ABCDEFGHIJKLMNOPQ".getBytes("US-ASCII")); + String outputString = "ABCDEFGH"; + byte[] outputBytes = outputString.getBytes("US-ASCII"); + int targetChunkSize = 3; + for (int i = 0; i < outputBytes.length; i += targetChunkSize) { + int count = i + targetChunkSize < outputBytes.length ? 3 : outputBytes.length - i; + outputStream.write(outputBytes, i, count); + outputStream.flush(); + } assertEquals(200, urlConnection.getResponseCode()); RecordedRequest request = server.takeRequest(); - assertEquals("ABCDEFGHIJKLMNOPQ", new String(request.getBody(), "US-ASCII")); - assertEquals(Arrays.asList(3, 3, 3, 3, 3, 2), request.getChunkSizes()); + assertEquals(outputString, new String(request.getBody(), "US-ASCII")); + assertEquals(Arrays.asList(3, 3, 2), request.getChunkSizes()); } public void testAuthenticateWithFixedLengthStreaming() throws Exception { @@ -1615,7 +1603,7 @@ public final class URLConnectionTest extends TestCase { + "CN=" + hostName + " 1, " + "CN=Test Intermediate Certificate Authority 1, " + "CN=Test Root Certificate Authority 1" - + "] RSA"), + + "] ECDHE_RSA"), trustManager.calls); } finally { HttpsURLConnection.setDefaultHostnameVerifier(defaultHostnameVerifier); @@ -2190,16 +2178,15 @@ public final class URLConnectionTest extends TestCase { } } + // http://code.google.com/p/android/issues/detail?id=16895 public void testUrlWithSpaceInHostViaHttpProxy() throws Exception { server.enqueue(new MockResponse()); server.play(); URLConnection urlConnection = new URL("http://and roid.com/") .openConnection(server.toProxyAddress()); - try { - urlConnection.getInputStream(); - fail(); // the RI makes a bogus proxy request for "GET http://and roid.com/ HTTP/1.1" - } catch (UnknownHostException expected) { - } + + // This test is to check that a NullPointerException is not thrown. + urlConnection.getInputStream(); } public void testSslFallback() throws Exception { @@ -2213,7 +2200,7 @@ public final class URLConnectionTest extends TestCase { "SSLv3"); server.useHttps(serverSocketFactory, false); - server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE)); + server.enqueue(new MockResponse().setSocketPolicy(FAIL_HANDSHAKE)); server.enqueue(new MockResponse().setBody("This required a 2nd handshake")); server.play(); @@ -2237,7 +2224,7 @@ public final class URLConnectionTest extends TestCase { SSLSocket clientSocket1 = createdSockets.get(0); List<String> clientSocket1EnabledProtocols = Arrays.asList( clientSocket1.getEnabledProtocols()); - assertContains(clientSocket1EnabledProtocols, "TLSv1"); + assertContains(clientSocket1EnabledProtocols, "TLSv1.2"); List<String> clientSocket1EnabledCiphers = Arrays.asList(clientSocket1.getEnabledCipherSuites()); assertContainsNoneMatching( @@ -2246,7 +2233,7 @@ public final class URLConnectionTest extends TestCase { SSLSocket clientSocket2 = createdSockets.get(1); List<String> clientSocket2EnabledProtocols = Arrays.asList(clientSocket2.getEnabledProtocols()); - assertContainsNoneMatching(clientSocket2EnabledProtocols, "TLSv1"); + assertContainsNoneMatching(clientSocket2EnabledProtocols, "TLSv1.2"); List<String> clientSocket2EnabledCiphers = Arrays.asList(clientSocket2.getEnabledCipherSuites()); assertContains(clientSocket2EnabledCiphers, StandardNames.CIPHER_SUITE_FALLBACK); @@ -2296,11 +2283,15 @@ public final class URLConnectionTest extends TestCase { HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection(); connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory()); connection.connect(); - assertNotNull(connection.getHostnameVerifier()); - assertNull(connection.getLocalCertificates()); - assertNotNull(connection.getServerCertificates()); - assertNotNull(connection.getCipherSuite()); - assertNotNull(connection.getPeerPrincipal()); + try { + assertNotNull(connection.getHostnameVerifier()); + assertNull(connection.getLocalCertificates()); + assertNotNull(connection.getServerCertificates()); + assertNotNull(connection.getCipherSuite()); + assertNotNull(connection.getPeerPrincipal()); + } finally { + connection.disconnect(); + } } /** diff --git a/luni/src/test/java/libcore/java/net/URLTest.java b/luni/src/test/java/libcore/java/net/URLTest.java index a18816b..07e651c 100644 --- a/luni/src/test/java/libcore/java/net/URLTest.java +++ b/luni/src/test/java/libcore/java/net/URLTest.java @@ -350,7 +350,7 @@ public final class URLTest extends TestCase { } } - public void testNegativePort() throws Exception { + public void testPortWithMinusSign() throws Exception { try { new URL("http://host:-2/"); fail(); @@ -358,6 +358,22 @@ public final class URLTest extends TestCase { } } + public void testPortWithPlusSign() throws Exception { + try { + new URL("http://host:+2/"); + fail(); + } catch (MalformedURLException expected) { + } + } + + public void testPortNonASCII() throws Exception { + try { + new URL("http://host:١٢٣/"); // 123 in arabic + fail(); + } catch (MalformedURLException expected) { + } + } + public void testNegativePortEqualsPlaceholder() throws Exception { try { new URL("http://host:-1/"); diff --git a/luni/src/test/java/libcore/java/nio/BufferTest.java b/luni/src/test/java/libcore/java/nio/BufferTest.java index ae90d49..c936cdf 100644 --- a/luni/src/test/java/libcore/java/nio/BufferTest.java +++ b/luni/src/test/java/libcore/java/nio/BufferTest.java @@ -16,12 +16,28 @@ package libcore.java.nio; -import java.io.*; -import java.lang.reflect.*; -import java.nio.*; -import java.nio.channels.*; -import java.util.Arrays; import junit.framework.TestCase; +import java.io.File; +import java.io.RandomAccessFile; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.nio.Buffer; +import java.nio.BufferOverflowException; +import java.nio.BufferUnderflowException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.CharBuffer; +import java.nio.DoubleBuffer; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; +import java.nio.LongBuffer; +import java.nio.MappedByteBuffer; +import java.nio.NioUtils; +import java.nio.ReadOnlyBufferException; +import java.nio.ShortBuffer; +import java.nio.channels.FileChannel; +import java.util.Arrays; +import libcore.io.SizeOf; public class BufferTest extends TestCase { private static ByteBuffer allocateMapped(int size) throws Exception { @@ -586,17 +602,31 @@ public class BufferTest extends TestCase { assertTrue(b.isDirect()); // Check the buffer has an array of the right size. assertTrue(b.hasArray()); - assertEquals(0, b.arrayOffset()); byte[] array = b.array(); - assertEquals(10, array.length); + assertTrue(array.length >= b.capacity()); + assertEquals(10, b.capacity()); // Check that writes to the array show up in the buffer. assertEquals(0, b.get(0)); - array[0] = 1; + array[b.arrayOffset()] = 1; assertEquals(1, b.get(0)); // Check that writes to the buffer show up in the array. - assertEquals(1, array[0]); + assertEquals(1, array[b.arrayOffset()]); b.put(0, (byte) 0); - assertEquals(0, array[0]); + assertEquals(0, array[b.arrayOffset()]); + } + + // Test that direct byte buffers are 8 byte aligned. + // http://b/16449607 + public void testDirectByteBufferAlignment() throws Exception { + ByteBuffer b = ByteBuffer.allocateDirect(10); + Field addressField = Buffer.class.getDeclaredField("effectiveDirectAddress"); + assertTrue(addressField != null); + addressField.setAccessible(true); + long address = addressField.getLong(b); + // Check that the address field is aligned by 8. + // Normally reading this field happens in native code by calling + // GetDirectBufferAddress. + assertEquals(0, address % 8); } public void testSliceOffset() throws Exception { @@ -604,14 +634,12 @@ public class BufferTest extends TestCase { ByteBuffer buffer = ByteBuffer.allocate(10); buffer.get(); ByteBuffer slice = buffer.slice(); - assertEquals(0, buffer.arrayOffset()); - assertEquals(1, slice.arrayOffset()); + assertEquals(buffer.arrayOffset() + 1, slice.arrayOffset()); ByteBuffer directBuffer = ByteBuffer.allocateDirect(10); directBuffer.get(); ByteBuffer directSlice = directBuffer.slice(); - assertEquals(0, directBuffer.arrayOffset()); - assertEquals(1, directSlice.arrayOffset()); + assertEquals(directBuffer.arrayOffset() + 1, directSlice.arrayOffset()); } // http://code.google.com/p/android/issues/detail?id=16184 @@ -855,4 +883,396 @@ public class BufferTest extends TestCase { mapped.flip(); mapped.get(); } + + public void testElementSizeShifts() { + // Element size shifts are the log base 2 of the element size + // of this buffer. + assertEquals(1, 1 << ByteBuffer.allocate(0).getElementSizeShift()); + + assertEquals(SizeOf.CHAR, 1 << CharBuffer.allocate(0).getElementSizeShift()); + assertEquals(SizeOf.SHORT, 1 << ShortBuffer.allocate(0).getElementSizeShift()); + + assertEquals(SizeOf.INT, 1 << IntBuffer.allocate(0).getElementSizeShift()); + assertEquals(SizeOf.FLOAT, 1 << FloatBuffer.allocate(0).getElementSizeShift()); + + assertEquals(SizeOf.LONG, 1 << LongBuffer.allocate(0).getElementSizeShift()); + assertEquals(SizeOf.DOUBLE, 1 << DoubleBuffer.allocate(0).getElementSizeShift()); + } + + public void testFreed() { + ByteBuffer b1 = ByteBuffer.allocateDirect(1); + ByteBuffer b2 = b1.duplicate(); + NioUtils.freeDirectBuffer(b1); + for (ByteBuffer b: new ByteBuffer[] { b1, b2 }) { + assertFalse(b.isAccessible()); + try { + b.compact(); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.duplicate(); + fail(); + } catch (IllegalStateException expected) { + } + testFailForPutMethods(b); + testFailForAsMethods(b); + testFailForGetMethods(b); + NioUtils.freeDirectBuffer(b); // should be able to free twice + } + } + + public void testAccess() { + ByteBuffer b1 = ByteBuffer.allocate(1); + ByteBuffer b2 = b1.duplicate(); + for (ByteBuffer b: new ByteBuffer[] { b1, b2 }) { + try { + b.setAccessible(true); + fail(); + } catch (UnsupportedOperationException expected) { + } + try { + b.setAccessible(false); + fail(); + } catch (UnsupportedOperationException expected) { + } + } + b1 = ByteBuffer.allocateDirect(8); + b2 = b1.duplicate(); + b1.setAccessible(false); + ByteBuffer b3 = b1.asReadOnlyBuffer(); + for (ByteBuffer b: new ByteBuffer[] { b1, b2, b3 }) { + b.duplicate(); + assertFalse(b.isAccessible()); + // even read-only buffers should fail with IllegalStateException + testFailForPutMethods(b); + testAsMethods(b); + testFailForGetMethods(b); + b.position(0); + b.limit(8); + try { + b.asCharBuffer().get(0); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.asShortBuffer().get(0); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.asIntBuffer().get(0); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.asLongBuffer().get(0); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.asFloatBuffer().get(0); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.asDoubleBuffer().get(0); + fail(); + } catch (IllegalStateException expected) { + } + } + b2.setAccessible(true); + for (ByteBuffer b: new ByteBuffer[] { b1, b2, b3 }) { + assertTrue(b.isAccessible()); + b.position(0); + b.limit(8); + b.asCharBuffer().get(0); + b.asShortBuffer().get(0); + b.asIntBuffer().get(0); + b.asLongBuffer().get(0); + b.asFloatBuffer().get(0); + b.asDoubleBuffer().get(0); + if (!b.isReadOnly()) { + testPutMethods(b); + b.compact(); + } else { + try { + b.put(0, (byte) 0); + fail(); + } catch (ReadOnlyBufferException expected) { + } + } + testAsMethods(b); + testGetMethods(b); + } + } + + private void testPutMethods(ByteBuffer b) { + b.position(0); + b.put((byte) 0); + b.put(0, (byte) 0); + b.put(new byte[1]); + b.put(new byte[1], 0, 1); + b.put(ByteBuffer.allocate(1)); + b.putChar('a'); + b.putChar(0, 'a'); + b.position(0); + b.putDouble(0); + b.putDouble(0, 0); + b.position(0); + b.putFloat(0); + b.putFloat(0, 0); + b.putInt(0); + b.putInt(0, 0); + b.position(0); + b.putLong(0); + b.putLong(0, 0); + b.position(0); + b.putShort((short) 0); + b.putShort(0, (short) 0); + } + + private void testFailForPutMethods(ByteBuffer b) { + try { + b.put((byte) 0); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.put(0, (byte) 0); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.put(new byte[1]); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.put(new byte[1], 0, 1); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.put(ByteBuffer.allocate(1)); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.putChar('a'); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.putChar(0, 'a'); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.putDouble(0); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.putDouble(0, 0); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.putFloat(0); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.putFloat(0, 0); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.putInt(0); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.putInt(0, 0); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.putLong(0); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.putLong(0, 0); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.putShort((short) 0); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.putShort(0, (short) 0); + fail(); + } catch (IllegalStateException expected) { + } + } + + private void testGetMethods(ByteBuffer b) { + b.position(0); + b.get(); + b.get(0); + b.get(new byte[1]); + b.get(new byte[1], 0, 1); + b.getChar(); + b.getChar(0); + b.position(0); + b.getDouble(); + b.getDouble(0); + b.position(0); + b.getFloat(); + b.getFloat(0); + b.getInt(); + b.getInt(0); + b.position(0); + b.getLong(); + b.getLong(0); + b.position(0); + b.getShort(); + b.getShort(0); + } + + private void testFailForGetMethods(ByteBuffer b) { + try { + b.get(); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.get(0); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.get(new byte[1]); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.get(new byte[1], 0, 1); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.getChar(); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.getChar(0); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.getDouble(); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.getDouble(0); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.getFloat(); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.getFloat(0); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.getInt(); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.getInt(0); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.getLong(); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.getLong(0); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.getShort(); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.getShort(0); + fail(); + } catch (IllegalStateException expected) { + } + } + + private void testAsMethods(ByteBuffer b) { + b.asCharBuffer(); + b.asDoubleBuffer(); + b.asFloatBuffer(); + b.asIntBuffer(); + b.asLongBuffer(); + b.asReadOnlyBuffer(); + b.asShortBuffer(); + } + + private void testFailForAsMethods(ByteBuffer b) { + try { + b.asCharBuffer(); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.asDoubleBuffer(); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.asFloatBuffer(); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.asIntBuffer(); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.asLongBuffer(); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.asReadOnlyBuffer(); + fail(); + } catch (IllegalStateException expected) { + } + try { + b.asShortBuffer(); + fail(); + } catch (IllegalStateException expected) { + } + } + } diff --git a/luni/src/test/java/libcore/java/nio/channels/DatagramChannelTest.java b/luni/src/test/java/libcore/java/nio/channels/DatagramChannelTest.java index 13757d2..efcfece 100644 --- a/luni/src/test/java/libcore/java/nio/channels/DatagramChannelTest.java +++ b/luni/src/test/java/libcore/java/nio/channels/DatagramChannelTest.java @@ -16,9 +16,19 @@ package libcore.java.nio.channels; +import java.io.IOException; import java.net.DatagramSocket; +import java.net.Inet4Address; +import java.net.Inet6Address; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.NetworkInterface; import java.nio.ByteBuffer; +import java.nio.channels.ClosedChannelException; import java.nio.channels.DatagramChannel; +import java.nio.channels.UnresolvedAddressException; +import java.util.Enumeration; +import java.util.Set; public class DatagramChannelTest extends junit.framework.TestCase { public void test_read_intoReadOnlyByteArrays() throws Exception { @@ -55,4 +65,110 @@ public class DatagramChannelTest extends junit.framework.TestCase { dc.close(); } } + + public void testInitialState() throws Exception { + DatagramChannel dc = DatagramChannel.open(); + try { + DatagramSocket socket = dc.socket(); + assertFalse(socket.isBound()); + assertFalse(socket.getBroadcast()); + assertFalse(socket.isClosed()); + assertFalse(socket.isConnected()); + assertEquals(0, socket.getLocalPort()); + assertTrue(socket.getLocalAddress().isAnyLocalAddress()); + assertNull(socket.getLocalSocketAddress()); + assertNull(socket.getInetAddress()); + assertEquals(-1, socket.getPort()); + assertNull(socket.getRemoteSocketAddress()); + assertFalse(socket.getReuseAddress()); + + assertSame(dc, socket.getChannel()); + } finally { + dc.close(); + } + } + + public void test_bind_unresolvedAddress() throws IOException { + DatagramChannel dc = DatagramChannel.open(); + try { + dc.socket().bind(new InetSocketAddress("unresolvedname", 31415)); + fail(); + } catch (IOException expected) { + } + + assertTrue(dc.isOpen()); + assertFalse(dc.isConnected()); + + dc.close(); + } + + public void test_bind_any_IPv4() throws Exception { + test_bind_any(InetAddress.getByName("0.0.0.0")); + } + + public void test_bind_any_IPv6() throws Exception { + test_bind_any(InetAddress.getByName("::")); + } + + private void test_bind_any(InetAddress bindAddress) throws Exception { + DatagramChannel dc = DatagramChannel.open(); + dc.socket().bind(new InetSocketAddress(bindAddress, 0)); + + assertTrue(dc.isOpen()); + assertFalse(dc.isConnected()); + + InetSocketAddress actualAddress = (InetSocketAddress) dc.socket().getLocalSocketAddress(); + assertTrue(actualAddress.getAddress().isAnyLocalAddress()); + assertTrue(actualAddress.getPort() > 0); + + dc.close(); + } + + public void test_bind_loopback_IPv4() throws Exception { + test_bind(InetAddress.getByName("127.0.0.1")); + } + + public void test_bind_loopback_IPv6() throws Exception { + test_bind(InetAddress.getByName("::1")); + } + + public void test_bind_IPv4() throws Exception { + InetAddress bindAddress = getNonLoopbackNetworkInterfaceAddress(true /* ipv4 */); + test_bind(bindAddress); + } + + public void test_bind_IPv6() throws Exception { + InetAddress bindAddress = getNonLoopbackNetworkInterfaceAddress(false /* ipv4 */); + test_bind(bindAddress); + } + + private void test_bind(InetAddress bindAddress) throws IOException { + DatagramChannel dc = DatagramChannel.open(); + dc.socket().bind(new InetSocketAddress(bindAddress, 0)); + + InetSocketAddress actualAddress = (InetSocketAddress) dc.socket().getLocalSocketAddress(); + assertEquals(bindAddress, actualAddress.getAddress()); + assertTrue(actualAddress.getPort() > 0); + + dc.close(); + } + + private static InetAddress getNonLoopbackNetworkInterfaceAddress(boolean ipv4) throws IOException { + Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); + while (networkInterfaces.hasMoreElements()) { + NetworkInterface networkInterface = networkInterfaces.nextElement(); + if (networkInterface.isLoopback() || !networkInterface.isUp()) { + continue; + } + Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses(); + while (inetAddresses.hasMoreElements()) { + InetAddress inetAddress = inetAddresses.nextElement(); + if ( (ipv4 && inetAddress instanceof Inet4Address) + || (!ipv4 && inetAddress instanceof Inet6Address)) { + return inetAddress; + } + } + } + return null; + } } diff --git a/luni/src/test/java/libcore/java/nio/channels/FileChannelTest.java b/luni/src/test/java/libcore/java/nio/channels/FileChannelTest.java index 415ae0a..babbf41 100644 --- a/luni/src/test/java/libcore/java/nio/channels/FileChannelTest.java +++ b/luni/src/test/java/libcore/java/nio/channels/FileChannelTest.java @@ -19,6 +19,8 @@ package libcore.java.nio.channels; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; +import java.io.IOException; +import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import libcore.io.IoUtils; @@ -110,4 +112,121 @@ public class FileChannelTest extends junit.framework.TestCase { assertEquals("hello world", new String(IoUtils.readFileAsString(tmp.getPath()))); } + + public void test_position_writeAddsPadding() throws Exception { + byte[] initialBytes = "12345".getBytes("US-ASCII"); + int initialFileSize = initialBytes.length; // 5 + FileChannel fc = createFileContainingBytes(initialBytes); + + int positionBeyondSize = 10; + fc.position(positionBeyondSize); + assertEquals(positionBeyondSize, fc.position()); + assertEquals(initialFileSize, fc.size()); + + byte[] newBytes = "6789A".getBytes("US-ASCII"); + fc.write(ByteBuffer.wrap(newBytes)); + + int expectedNewLength = positionBeyondSize + newBytes.length; + assertEquals(expectedNewLength, fc.position()); + assertEquals(expectedNewLength, fc.size()); + + fc.close(); + } + + public void test_truncate_greaterThanSizeWithPositionChange() throws Exception { + byte[] initialBytes = "12345".getBytes("US-ASCII"); + int initialFileSize = initialBytes.length; // 5 + FileChannel fc = createFileContainingBytes(initialBytes); + + int initialPosition = 40; + fc.position(initialPosition); // Should not affect the file size + assertEquals(initialPosition, fc.position()); + assertEquals(initialFileSize, fc.size()); + + // truncateArg < position, truncateArg > initialFileSize: Should not affect the file size + // and should move the position. + int truncateArg = 10; + fc.truncate(truncateArg); // Should not affect the file size, but should move the position. + assertEquals(initialFileSize, fc.size()); + // The RI does not behave properly here, according to the docs for truncate(), position() + // should now be the same as truncateArg. + assertEquals(truncateArg, fc.position()); + + fc.close(); + } + + public void test_truncate_greaterThanSizeWithoutPositionChange() throws Exception { + byte[] initialBytes = "123456789A".getBytes("US-ASCII"); + int initialFileSize = initialBytes.length; // 10 + FileChannel fc = createFileContainingBytes(initialBytes); + + int initialPosition = 5; + fc.position(initialPosition); + assertEquals(initialPosition, fc.position()); + assertEquals(initialFileSize, fc.size()); + + // truncateArg > position, truncateArg > initialFileSize: Should not affect the file size + // and should not move the position. + int truncateArg = 15; + fc.truncate(truncateArg); + assertEquals(initialFileSize, fc.size()); + assertEquals(initialPosition, fc.position()); + + fc.close(); + } + + public void test_truncate_lessThanSizeWithPositionChange() throws Exception { + byte[] initialBytes = "123456789A".getBytes("US-ASCII"); + int initialFileSize = initialBytes.length; // 10 + FileChannel fc = createFileContainingBytes(initialBytes); + + int initialPosition = initialFileSize; + fc.position(initialPosition); + assertEquals(initialPosition, fc.position()); + assertEquals(initialFileSize, fc.size()); + + int truncateArg = 5; + // truncateArg < initialPosition, truncateArg < initialFileSize: Should affect the file size + // and should move the position. + fc.truncate(truncateArg); + assertEquals(truncateArg, fc.size()); + assertEquals(truncateArg, fc.position()); + + fc.close(); + } + + public void test_truncate_lessThanSizeWithoutPositionChange() throws Exception { + byte[] initialBytes = "123456789A".getBytes("US-ASCII"); + int initialFileSize = initialBytes.length; // 10 + FileChannel fc = createFileContainingBytes(initialBytes); + + int initialPosition = 4; + fc.position(initialPosition); + assertEquals(initialPosition, fc.position()); + assertEquals(initialFileSize, fc.size()); + + int truncateArg = 5; + // truncateArg > initialPosition, truncateArg < initialFileSize: Should affect the file size + // and should not move the position. + fc.truncate(truncateArg); + assertEquals(truncateArg, fc.size()); + assertEquals(initialPosition, fc.position()); + + fc.close(); + } + + private static FileChannel createFileContainingBytes(byte[] bytes) throws IOException { + File tmp = File.createTempFile("FileChannelTest", "tmp"); + FileOutputStream fos = new FileOutputStream(tmp, true); + FileChannel fc = fos.getChannel(); + fc.write(ByteBuffer.wrap(bytes)); + fc.close(); + + assertEquals(bytes.length, tmp.length()); + + fc = new RandomAccessFile(tmp, "rw").getChannel(); + assertEquals(bytes.length, fc.size()); + + return fc; + } } diff --git a/luni/src/test/java/libcore/java/nio/channels/FileIOInterruptTest.java b/luni/src/test/java/libcore/java/nio/channels/FileIOInterruptTest.java new file mode 100644 index 0000000..02c6f3b --- /dev/null +++ b/luni/src/test/java/libcore/java/nio/channels/FileIOInterruptTest.java @@ -0,0 +1,709 @@ +/* + * Copyright (C) 2014 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.nio.channels; + +import junit.framework.TestCase; + +import android.system.OsConstants; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InterruptedIOException; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.AsynchronousCloseException; +import java.nio.channels.ClosedByInterruptException; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.FileChannel; +import libcore.io.Libcore; + +import static libcore.io.IoUtils.closeQuietly; + +/** + * A test for file interrupt behavior. Because forcing a real file to block on read or write is + * difficult this test uses Unix FIFO / Named Pipes. FIFOs appear to Java as files but the test + * has more control over the available data. Reader will block until the other end writes, and + * writers can also be made to block. + * + * <p>Using FIFOs has a few drawbacks: + * <ol> + * <li>FIFOs are not supported from Java or the command-line on Android, so this test includes + * native code to create the FIFO. + * <li>FIFOs will not open() until there is both a reader and a writer of the FIFO; each test must + * always attach both ends or experience a blocked test. + * <li>FIFOs are not supported on some file systems. e.g. VFAT, so the test has to be particular + * about the temporary directory it uses to hold the FIFO. + * <li>Writes to FIFOs are buffered by the OS which makes blocking behavior more difficult to + * induce. See {@link ChannelWriter} and {@link StreamWriter}. + * </ol> + */ +public class FileIOInterruptTest extends TestCase { + + private static File VOGAR_DEVICE_TEMP_DIR = new File("/data/data/file_io_interrupt_test"); + + private File fifoFile; + + @Override + public void setUp() throws Exception { + super.setUp(); + + // This test relies on a FIFO file. The file system must support FIFOs, so we check the path. + String tmpDirName = System.getProperty("java.io.tmpdir"); + File tmpDir; + if (tmpDirName.startsWith("/sdcard")) { + // Vogar execution on device runs in /sdcard. Unfortunately the file system used does not + // support FIFOs so the test must use one that is more likely to work. + if (!VOGAR_DEVICE_TEMP_DIR.exists()) { + assertTrue(VOGAR_DEVICE_TEMP_DIR.mkdir()); + } + VOGAR_DEVICE_TEMP_DIR.deleteOnExit(); + tmpDir = VOGAR_DEVICE_TEMP_DIR; + } else { + tmpDir = new File(tmpDirName); + } + fifoFile = new File(tmpDir, "fifo_file.tmp"); + if (fifoFile.exists()) { + fifoFile.delete(); + } + fifoFile.deleteOnExit(); + + // Create the fifo. This will throw an exception if the file system does not support it. + Libcore.os.mkfifo(fifoFile.getAbsolutePath(), OsConstants.S_IRWXU); + } + + @Override + public void tearDown() throws Exception { + super.tearDown(); + fifoFile.delete(); + VOGAR_DEVICE_TEMP_DIR.delete(); + + // Clear the interrupted state, if set. + Thread.interrupted(); + } + + public void testStreamRead_exceptionWhenAlreadyClosed() throws Exception { + FifoWriter fifoWriter = new FifoWriter(fifoFile); + fifoWriter.start(); + + FileInputStream fis = new FileInputStream(fifoFile); + fis.close(); + + byte[] buffer = new byte[10]; + try { + fis.read(buffer); + fail(); + } catch (IOException expected) { + assertSame(IOException.class, expected.getClass()); + } + + fifoWriter.tidyUp(); + } + + // This test fails on the RI: close() does not wake up a blocking FileInputStream.read() call. + public void testStreamRead_exceptionOnCloseWhenBlocked() throws Exception { + FifoWriter fifoWriter = new FifoWriter(fifoFile); + fifoWriter.start(); + + FileInputStream fis = new FileInputStream(fifoFile); + StreamReader streamReader = new StreamReader(fis); + Thread streamReaderThread = createAndStartThread("StreamReader", streamReader); + + // Delay until we can be fairly sure the reader thread is blocking. + streamReader.waitForThreadToBlock(); + + // Now close the OutputStream to see what happens. + fis.close(); + + // Test for expected behavior in the reader thread. + waitToDie(streamReaderThread); + assertSame(InterruptedIOException.class, streamReader.ioe.getClass()); + assertFalse(streamReader.wasInterrupted); + + // Tidy up the writer thread. + fifoWriter.tidyUp(); + } + + public void testStreamWrite_exceptionWhenAlreadyClosed() throws Exception { + FifoReader fifoReader = new FifoReader(fifoFile); + fifoReader.start(); + + FileOutputStream fos = new FileOutputStream(fifoFile); + byte[] buffer = new byte[10]; + fos.close(); + + try { + fos.write(buffer); + fail(); + } catch (IOException expected) { + assertSame(IOException.class, expected.getClass()); + } + + fifoReader.tidyUp(); + } + + // This test fails on the RI: close() does not wake up a blocking FileInputStream.write() call. + public void testStreamWrite_exceptionOnCloseWhenBlocked() throws Exception { + FifoReader fifoReader = new FifoReader(fifoFile); + fifoReader.start(); + + FileOutputStream fos = new FileOutputStream(fifoFile); + StreamWriter streamWriter = new StreamWriter(fos); + Thread streamWriterThread = createAndStartThread("StreamWriter", streamWriter); + + // Delay until we can be fairly sure the writer thread is blocking. + streamWriter.waitForThreadToBlock(); + + // Now close the OutputStream to see what happens. + fos.close(); + + // Test for expected behavior in the writer thread. + waitToDie(streamWriterThread); + assertSame(InterruptedIOException.class, streamWriter.ioe.getClass()); + assertFalse(streamWriter.wasInterrupted); + + // Tidy up the reader thread. + fifoReader.tidyUp(); + } + + public void testChannelRead_exceptionWhenAlreadyClosed() throws Exception { + testChannelRead_exceptionWhenAlreadyClosed(ChannelReader.Method.READ); + } + + public void testChannelReadV_exceptionWhenAlreadyClosed() throws Exception { + testChannelRead_exceptionWhenAlreadyClosed(ChannelReader.Method.READV); + } + + private void testChannelRead_exceptionWhenAlreadyClosed(ChannelReader.Method method) + throws Exception { + FifoWriter fifoWriter = new FifoWriter(fifoFile); + fifoWriter.start(); + FileInputStream fis = new FileInputStream(fifoFile); + FileChannel fileInputChannel = fis.getChannel(); + fileInputChannel.close(); + + ByteBuffer buffer = ByteBuffer.allocateDirect(10); + try { + if (method == ChannelReader.Method.READ) { + fileInputChannel.read(buffer); + } else { + ByteBuffer buffer2 = ByteBuffer.allocateDirect(10); + fileInputChannel.read(new ByteBuffer[] { buffer, buffer2}); + } + fail(); + } catch (IOException expected) { + assertSame(ClosedChannelException.class, expected.getClass()); + } + + fifoWriter.tidyUp(); + } + + public void testChannelRead_exceptionWhenAlreadyInterrupted() throws Exception { + testChannelRead_exceptionWhenAlreadyInterrupted(ChannelReader.Method.READ); + } + + public void testChannelReadV_exceptionWhenAlreadyInterrupted() throws Exception { + testChannelRead_exceptionWhenAlreadyInterrupted(ChannelReader.Method.READV); + } + + private void testChannelRead_exceptionWhenAlreadyInterrupted(ChannelReader.Method method) + throws Exception { + FifoWriter fifoWriter = new FifoWriter(fifoFile); + fifoWriter.start(); + FileInputStream fis = new FileInputStream(fifoFile); + FileChannel fileInputChannel = fis.getChannel(); + + Thread.currentThread().interrupt(); + + ByteBuffer buffer = ByteBuffer.allocateDirect(10); + try { + if (method == ChannelReader.Method.READ) { + fileInputChannel.read(buffer); + } else { + ByteBuffer buffer2 = ByteBuffer.allocateDirect(10); + fileInputChannel.read(new ByteBuffer[] { buffer, buffer2}); + } + fail(); + } catch (IOException expected) { + assertSame(ClosedByInterruptException.class, expected.getClass()); + } + + // Check but also clear the interrupted status, so we can wait for the FifoWriter thread in + // tidyUp(). + assertTrue(Thread.interrupted()); + + fifoWriter.tidyUp(); + } + + public void testChannelRead_exceptionOnCloseWhenBlocked() throws Exception { + testChannelRead_exceptionOnCloseWhenBlocked(ChannelReader.Method.READ); + } + + public void testChannelReadV_exceptionOnCloseWhenBlocked() throws Exception { + testChannelRead_exceptionOnCloseWhenBlocked(ChannelReader.Method.READV); + } + + private void testChannelRead_exceptionOnCloseWhenBlocked(ChannelReader.Method method) + throws Exception { + FifoWriter fifoWriter = new FifoWriter(fifoFile); + fifoWriter.start(); + FileInputStream fis = new FileInputStream(fifoFile); + FileChannel fileInputChannel = fis.getChannel(); + + ChannelReader channelReader = new ChannelReader(fileInputChannel, method); + Thread channelReaderThread = createAndStartThread("ChannelReader", channelReader); + + // Delay until we can be fairly sure the reader thread is blocking. + channelReader.waitForThreadToBlock(); + + // Now close the FileChannel to see what happens. + fileInputChannel.close(); + + // Test for expected behavior in the reader thread. + waitToDie(channelReaderThread); + assertSame(AsynchronousCloseException.class, channelReader.ioe.getClass()); + assertFalse(channelReader.wasInterrupted); + + // Tidy up the writer thread. + fifoWriter.tidyUp(); + } + + public void testChannelRead_exceptionOnInterrupt() throws Exception { + testChannelRead_exceptionOnInterrupt(ChannelReader.Method.READ); + } + + public void testChannelReadV_exceptionOnInterrupt() throws Exception { + testChannelRead_exceptionOnInterrupt(ChannelReader.Method.READV); + } + + private void testChannelRead_exceptionOnInterrupt(ChannelReader.Method method) throws Exception { + FifoWriter fifoWriter = new FifoWriter(fifoFile); + fifoWriter.start(); + FileChannel fileChannel = new FileInputStream(fifoFile).getChannel(); + + ChannelReader channelReader = new ChannelReader(fileChannel, method); + Thread channelReaderThread = createAndStartThread("ChannelReader", channelReader); + + // Delay until we can be fairly sure the reader thread is blocking. + channelReader.waitForThreadToBlock(); + + // Now interrupt the reader thread to see what happens. + channelReaderThread.interrupt(); + + // Test for expected behavior in the reader thread. + waitToDie(channelReaderThread); + assertSame(ClosedByInterruptException.class, channelReader.ioe.getClass()); + assertTrue(channelReader.wasInterrupted); + + // Tidy up the writer thread. + fifoWriter.tidyUp(); + } + + public void testChannelWrite_exceptionWhenAlreadyClosed() throws Exception { + testChannelWrite_exceptionWhenAlreadyClosed(ChannelWriter.Method.WRITE); + } + + public void testChannelWriteV_exceptionWhenAlreadyClosed() throws Exception { + testChannelWrite_exceptionWhenAlreadyClosed(ChannelWriter.Method.WRITEV); + } + + private void testChannelWrite_exceptionWhenAlreadyClosed(ChannelWriter.Method method) + throws Exception { + FifoReader fifoReader = new FifoReader(fifoFile); + fifoReader.start(); + FileChannel fileOutputChannel = new FileOutputStream(fifoFile).getChannel(); + fileOutputChannel.close(); + + ByteBuffer buffer = ByteBuffer.allocateDirect(10); + try { + if (method == ChannelWriter.Method.WRITE) { + fileOutputChannel.write(buffer); + } else { + ByteBuffer buffer2 = ByteBuffer.allocateDirect(10); + fileOutputChannel.write(new ByteBuffer[] { buffer, buffer2 }); + } + fail(); + } catch (IOException expected) { + assertSame(ClosedChannelException.class, expected.getClass()); + } + + fifoReader.tidyUp(); + } + + public void testChannelWrite_exceptionWhenAlreadyInterrupted() throws Exception { + testChannelWrite_exceptionWhenAlreadyInterrupted(ChannelWriter.Method.WRITE); + } + + public void testChannelWriteV_exceptionWhenAlreadyInterrupted() throws Exception { + testChannelWrite_exceptionWhenAlreadyInterrupted(ChannelWriter.Method.WRITEV); + } + + private void testChannelWrite_exceptionWhenAlreadyInterrupted(ChannelWriter.Method method) + throws Exception { + FifoReader fifoReader = new FifoReader(fifoFile); + fifoReader.start(); + FileOutputStream fos = new FileOutputStream(fifoFile); + FileChannel fileInputChannel = fos.getChannel(); + + Thread.currentThread().interrupt(); + + ByteBuffer buffer = ByteBuffer.allocateDirect(10); + try { + if (method == ChannelWriter.Method.WRITE) { + fileInputChannel.write(buffer); + } else { + ByteBuffer buffer2 = ByteBuffer.allocateDirect(10); + fileInputChannel.write(new ByteBuffer[] { buffer, buffer2 }); + } + fail(); + } catch (IOException expected) { + assertSame(ClosedByInterruptException.class, expected.getClass()); + } + + // Check but also clear the interrupted status, so we can wait for the FifoReader thread in + // tidyUp(). + assertTrue(Thread.interrupted()); + + fifoReader.tidyUp(); + } + + public void testChannelWrite_exceptionOnCloseWhenBlocked() throws Exception { + testChannelWrite_exceptionOnCloseWhenBlocked(ChannelWriter.Method.WRITE); + } + + public void testChannelWriteV_exceptionOnCloseWhenBlocked() throws Exception { + testChannelWrite_exceptionOnCloseWhenBlocked(ChannelWriter.Method.WRITEV); + } + + private void testChannelWrite_exceptionOnCloseWhenBlocked(ChannelWriter.Method method) + throws Exception { + FifoReader fifoReader = new FifoReader(fifoFile); + fifoReader.start(); + FileChannel fileOutputChannel = new FileOutputStream(fifoFile).getChannel(); + + ChannelWriter channelWriter = new ChannelWriter(fileOutputChannel, method); + Thread channelWriterThread = createAndStartThread("ChannelWriter", channelWriter); + + // Delay until we can be fairly sure the writer thread is blocking. + channelWriter.waitForThreadToBlock(); + + // Now close the channel to see what happens. + fileOutputChannel.close(); + + // Test for expected behavior in the writer thread. + waitToDie(channelWriterThread); + // The RI throws ChannelClosedException. AsynchronousCloseException is more correct according to + // the docs. + assertSame(AsynchronousCloseException.class, channelWriter.ioe.getClass()); + assertFalse(channelWriter.wasInterrupted); + + // Tidy up the writer thread. + fifoReader.tidyUp(); + } + + public void testChannelWrite_exceptionOnInterrupt() throws Exception { + testChannelWrite_exceptionOnInterrupt(ChannelWriter.Method.WRITE); + } + + public void testChannelWriteV_exceptionOnInterrupt() throws Exception { + testChannelWrite_exceptionOnInterrupt(ChannelWriter.Method.WRITEV); + } + + private void testChannelWrite_exceptionOnInterrupt(ChannelWriter.Method method) throws Exception { + FifoReader fifoReader = new FifoReader(fifoFile); + fifoReader.start(); + + FileChannel fileChannel = new FileOutputStream(fifoFile).getChannel(); + ChannelWriter channelWriter = new ChannelWriter(fileChannel, method); + Thread channelWriterThread = createAndStartThread("ChannelWriter", channelWriter); + + // Delay until we can be fairly sure the writer thread is blocking. + channelWriter.waitForThreadToBlock(); + + // Now interrupt the writer thread to see what happens. + channelWriterThread.interrupt(); + + // Test for expected behavior in the writer thread. + waitToDie(channelWriterThread); + assertSame(ClosedByInterruptException.class, channelWriter.ioe.getClass()); + assertTrue(channelWriter.wasInterrupted); + + // Tidy up the reader thread. + fifoReader.tidyUp(); + } + + private static class StreamReader implements Runnable { + + private final FileInputStream inputStream; + volatile boolean started; + volatile IOException ioe; + volatile boolean wasInterrupted; + + StreamReader(FileInputStream inputStream) { + this.inputStream = inputStream; + } + + @Override + public void run() { + byte[] buffer = new byte[10]; + try { + started = true; + int bytesRead = inputStream.read(buffer); + fail("This isn't supposed to happen: read() returned: " + bytesRead); + } catch (IOException e) { + this.ioe = e; + } + wasInterrupted = Thread.interrupted(); + } + + public void waitForThreadToBlock() { + for (int i = 0; i < 10 && !started; i++) { + delay(100); + } + assertTrue(started); + // Just give it some more time to start blocking. + delay(100); + } + } + + private static class StreamWriter implements Runnable { + + private final FileOutputStream outputStream; + volatile int bytesWritten; + volatile IOException ioe; + volatile boolean wasInterrupted; + + StreamWriter(FileOutputStream outputStream) { + this.outputStream = outputStream; + } + + @Override + public void run() { + // Writes to FIFOs are buffered. We try to fill the buffer and induce blocking (the + // buffer is typically 64k). + byte[] buffer = new byte[10000]; + while (true) { + try { + outputStream.write(buffer); + bytesWritten += buffer.length; + } catch (IOException e) { + this.ioe = e; + break; + } + wasInterrupted = Thread.interrupted(); + } + } + + public void waitForThreadToBlock() { + int lastCount = bytesWritten; + for (int i = 0; i < 10; i++) { + delay(500); + int newBytesWritten = bytesWritten; + if (newBytesWritten > 0 && lastCount == newBytesWritten) { + // The thread is probably blocking. + return; + } + lastCount = bytesWritten; + } + fail("Writer never started blocking. Bytes written: " + bytesWritten); + } + } + + private static class ChannelReader implements Runnable { + enum Method { + READ, + READV, + } + + private final FileChannel channel; + private final Method method; + volatile boolean started; + volatile IOException ioe; + volatile boolean wasInterrupted; + + ChannelReader(FileChannel channel, Method method) { + this.channel = channel; + this.method = method; + } + + @Override + public void run() { + ByteBuffer buffer = ByteBuffer.allocateDirect(10); + try { + started = true; + if (method == Method.READ) { + channel.read(buffer); + } else { + ByteBuffer buffer2 = ByteBuffer.allocateDirect(10); + channel.read(new ByteBuffer[] { buffer, buffer2 }); + } + fail("All tests should block until an exception"); + } catch (IOException e) { + this.ioe = e; + } + wasInterrupted = Thread.interrupted(); + } + + public void waitForThreadToBlock() { + for (int i = 0; i < 10 && !started; i++) { + delay(100); + } + assertTrue(started); + // Just give it some more time to start blocking. + delay(100); + } + } + + private static class ChannelWriter implements Runnable { + enum Method { + WRITE, + WRITEV, + } + + private final FileChannel channel; + private final Method method; + volatile int bytesWritten; + volatile IOException ioe; + volatile boolean wasInterrupted; + + ChannelWriter(FileChannel channel, Method method) { + this.channel = channel; + this.method = method; + } + + @Override + public void run() { + ByteBuffer buffer1 = ByteBuffer.allocateDirect(10000); + ByteBuffer buffer2 = ByteBuffer.allocateDirect(10000); + // Writes to FIFOs are buffered. We try to fill the buffer and induce blocking (the + // buffer is typically 64k). + while (true) { + // Make the buffers look non-empty. + buffer1.position(0).limit(buffer1.capacity()); + buffer2.position(0).limit(buffer2.capacity()); + try { + if (method == Method.WRITE) { + bytesWritten += channel.write(buffer1); + } else { + bytesWritten += channel.write(new ByteBuffer[]{ buffer1, buffer2 }); + } + } catch (IOException e) { + this.ioe = e; + break; + } + } + wasInterrupted = Thread.interrupted(); + } + + public void waitForThreadToBlock() { + int lastCount = bytesWritten; + for (int i = 0; i < 10; i++) { + delay(500); + int newBytesWritten = bytesWritten; + if (newBytesWritten > 0 && lastCount == newBytesWritten) { + // The thread is probably blocking. + return; + } + lastCount = bytesWritten; + } + fail("Writer never started blocking. Bytes written: " + bytesWritten); + } + } + + /** + * Opens a FIFO for writing. Exists to unblock the other end of the FIFO. + */ + private static class FifoWriter extends Thread { + + private final File file; + private FileOutputStream fos; + + public FifoWriter(File file) { + super("FifoWriter"); + this.file = file; + } + + @Override + public void run() { + try { + fos = new FileOutputStream(file); + } catch (IOException ignored) { + } + } + + public void tidyUp() { + FileIOInterruptTest.waitToDie(this); + closeQuietly(fos); + } + } + + /** + * Opens a FIFO for reading. Exists to unblock the other end of the FIFO. + */ + private static class FifoReader extends Thread { + + private final File file; + private FileInputStream fis; + + public FifoReader(File file) { + super("FifoReader"); + this.file = file; + } + + @Override + public void run() { + try { + fis = new FileInputStream(file); + } catch (IOException ignored) { + } + } + + public void tidyUp() { + FileIOInterruptTest.waitToDie(this); + closeQuietly(fis); + } + } + + private static Thread createAndStartThread(String name, Runnable runnable) { + Thread t = new Thread(runnable, name); + t.setDaemon(true); + t.start(); + return t; + } + + private static void waitToDie(Thread thread) { + // Protect against this thread already being interrupted, which would prevent the test waiting + // for the requested time. + assertFalse(Thread.currentThread().isInterrupted()); + try { + thread.join(5000); + } catch (InterruptedException ignored) { + } + + if (thread.isAlive()) { + fail("Thread \"" + thread.getName() + "\" did not exit."); + } + } + + private static void delay(int millis) { + // Protect against this thread being interrupted, which would prevent us waiting. + assertFalse(Thread.currentThread().isInterrupted()); + try { + Thread.sleep(millis); + } catch (InterruptedException ignored) { + } + } + +} diff --git a/luni/src/test/java/libcore/java/nio/channels/OldSocketChannelTest.java b/luni/src/test/java/libcore/java/nio/channels/OldSocketChannelTest.java index 6560a7b..f849c33 100644 --- a/luni/src/test/java/libcore/java/nio/channels/OldSocketChannelTest.java +++ b/luni/src/test/java/libcore/java/nio/channels/OldSocketChannelTest.java @@ -17,9 +17,7 @@ package libcore.java.nio.channels; -import dalvik.annotation.BrokenTest; import java.io.IOException; -import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; @@ -198,14 +196,12 @@ public class OldSocketChannelTest extends TestCase { // expected } - SocketChannel channel1IP = null; try { - channel1IP = SocketChannel.open(null); + SocketChannel.open(null); fail("Should throw an IllegalArgumentException"); } catch (IllegalArgumentException e) { // correct } - assertNull(channel1IP); } private void ensureServerClosed() throws IOException { @@ -238,7 +234,7 @@ public class OldSocketChannelTest extends TestCase { return connected; } - @BrokenTest("Occasionally fail in CTS, but works in CoreTestRunner") + // Broken Test: Occasionally fail in CTS, but works in CoreTestRunner public void test_writeLjava_nio_ByteBuffer_Nonblocking_HugeData() throws IOException { // initialize write content ByteBuffer writeContent = ByteBuffer.allocate(CAPACITY_HUGE); @@ -355,48 +351,59 @@ public class OldSocketChannelTest extends TestCase { isConstructorCalled = true; } + @Override public Socket socket() { return null; } + @Override public boolean isConnected() { return false; } + @Override public boolean isConnectionPending() { return false; } + @Override public boolean connect(SocketAddress address) throws IOException { return false; } + @Override public boolean finishConnect() throws IOException { return false; } + @Override public int read(ByteBuffer target) throws IOException { return 0; } + @Override public long read(ByteBuffer[] targets, int offset, int length) throws IOException { return 0; } + @Override public int write(ByteBuffer source) throws IOException { return 0; } + @Override public long write(ByteBuffer[] sources, int offset, int length) throws IOException { return 0; } + @Override protected void implCloseSelectableChannel() throws IOException { // empty } + @Override protected void implConfigureBlocking(boolean blockingMode) throws IOException { // empty diff --git a/luni/src/test/java/libcore/java/nio/channels/SelectorTest.java b/luni/src/test/java/libcore/java/nio/channels/SelectorTest.java index b45f8e1..c5f449e 100644 --- a/luni/src/test/java/libcore/java/nio/channels/SelectorTest.java +++ b/luni/src/test/java/libcore/java/nio/channels/SelectorTest.java @@ -15,6 +15,7 @@ */ package libcore.java.nio.channels; +import android.system.OsConstants; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; @@ -26,9 +27,8 @@ import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import libcore.io.Libcore; -import libcore.io.OsConstants; import junit.framework.TestCase; +import libcore.io.Libcore; import tests.net.StuckServer; public class SelectorTest extends TestCase { @@ -93,11 +93,15 @@ public class SelectorTest extends TestCase { // http://code.google.com/p/android/issues/detail?id=15388 public void testInterrupted() throws IOException { Selector selector = Selector.open(); + Thread.currentThread().interrupt(); try { - Thread.currentThread().interrupt(); int count = selector.select(); assertEquals(0, count); + assertTrue(Thread.currentThread().isInterrupted()); } finally { + // Clear the interrupted thread state so that it does not interfere with later tests. + Thread.interrupted(); + selector.close(); } } diff --git a/luni/src/test/java/libcore/java/nio/channels/ServerSocketChannelTest.java b/luni/src/test/java/libcore/java/nio/channels/ServerSocketChannelTest.java index e66096c..1178b70 100644 --- a/luni/src/test/java/libcore/java/nio/channels/ServerSocketChannelTest.java +++ b/luni/src/test/java/libcore/java/nio/channels/ServerSocketChannelTest.java @@ -16,7 +16,18 @@ package libcore.java.nio.channels; +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.NetworkInterface; +import java.net.ServerSocket; +import java.net.SocketException; +import java.nio.channels.ClosedChannelException; import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; +import java.nio.channels.UnresolvedAddressException; +import java.util.Enumeration; +import java.util.Set; public class ServerSocketChannelTest extends junit.framework.TestCase { // http://code.google.com/p/android/issues/detail?id=16579 @@ -31,4 +42,107 @@ public class ServerSocketChannelTest extends junit.framework.TestCase { ssc.close(); } } + + /** Checks the state of the ServerSocketChannel and associated ServerSocket after open() */ + public void test_open_initialState() throws Exception { + ServerSocketChannel ssc = ServerSocketChannel.open(); + try { + assertNull(ssc.socket().getLocalSocketAddress()); + + ServerSocket socket = ssc.socket(); + assertFalse(socket.isBound()); + assertFalse(socket.isClosed()); + assertEquals(-1, socket.getLocalPort()); + assertNull(socket.getLocalSocketAddress()); + assertNull(socket.getInetAddress()); + assertTrue(socket.getReuseAddress()); + + assertSame(ssc, socket.getChannel()); + } finally { + ssc.close(); + } + } + + public void test_bind_unresolvedAddress() throws IOException { + ServerSocketChannel ssc = ServerSocketChannel.open(); + try { + ssc.socket().bind(new InetSocketAddress("unresolvedname", 31415)); + fail(); + } catch (SocketException expected) { + } + + assertNull(ssc.socket().getLocalSocketAddress()); + assertTrue(ssc.isOpen()); + + ssc.close(); + } + + public void test_bind_nullBindsToAll() throws Exception { + ServerSocketChannel ssc = ServerSocketChannel.open(); + ssc.socket().bind(null); + InetSocketAddress boundAddress = (InetSocketAddress) ssc.socket().getLocalSocketAddress(); + assertTrue(boundAddress.getAddress().isAnyLocalAddress()); + assertFalse(boundAddress.getAddress().isLinkLocalAddress()); + assertFalse(boundAddress.getAddress().isLoopbackAddress()); + + // Attempt to connect to the "any" address. + assertTrue(canConnect(boundAddress)); + + // Go through all local IPs and try to connect to each in turn - all should succeed. + Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); + while (interfaces.hasMoreElements()) { + NetworkInterface nic = interfaces.nextElement(); + Enumeration<InetAddress> inetAddresses = nic.getInetAddresses(); + while (inetAddresses.hasMoreElements()) { + InetSocketAddress address = + new InetSocketAddress(inetAddresses.nextElement(), boundAddress.getPort()); + assertTrue(canConnect(address)); + } + } + + ssc.close(); + } + + public void test_bind_loopback() throws Exception { + ServerSocketChannel ssc = ServerSocketChannel.open(); + ssc.socket().bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0)); + InetSocketAddress boundAddress = (InetSocketAddress) ssc.socket().getLocalSocketAddress(); + assertFalse(boundAddress.getAddress().isAnyLocalAddress()); + assertFalse(boundAddress.getAddress().isLinkLocalAddress()); + assertTrue(boundAddress.getAddress().isLoopbackAddress()); + + // Attempt to connect to the "loopback" address. Note: There can be several loopback + // addresses, such as 127.0.0.1 (IPv4) and 0:0:0:0:0:0:0:1 (IPv6) and only one will be + // bound. + InetSocketAddress loopbackAddress = + new InetSocketAddress(InetAddress.getLoopbackAddress(), boundAddress.getPort()); + assertTrue(canConnect(loopbackAddress)); + + // Go through all local IPs and try to connect to each in turn - all should fail except + // for the loopback. + Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); + while (interfaces.hasMoreElements()) { + NetworkInterface nic = interfaces.nextElement(); + Enumeration<InetAddress> inetAddresses = nic.getInetAddresses(); + while (inetAddresses.hasMoreElements()) { + InetSocketAddress address = + new InetSocketAddress(inetAddresses.nextElement(), boundAddress.getPort()); + if (!address.equals(loopbackAddress)) { + assertFalse(canConnect(address)); + } + } + } + + ssc.close(); + } + + private static boolean canConnect(InetSocketAddress address) { + try { + SocketChannel socketChannel = SocketChannel.open(address); + socketChannel.close(); + return true; + } catch (IOException e) { + return false; + } + } } diff --git a/luni/src/test/java/libcore/java/nio/channels/SocketChannelTest.java b/luni/src/test/java/libcore/java/nio/channels/SocketChannelTest.java index 6ab91ab..a54b30a 100644 --- a/luni/src/test/java/libcore/java/nio/channels/SocketChannelTest.java +++ b/luni/src/test/java/libcore/java/nio/channels/SocketChannelTest.java @@ -16,26 +16,37 @@ package libcore.java.nio.channels; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import java.net.ConnectException; +import java.net.Socket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; +import java.nio.channels.SocketChannel; import java.nio.channels.Selector; import java.nio.channels.SelectionKey; -import java.nio.channels.SocketChannel; +import java.nio.channels.UnresolvedAddressException; +import java.util.Set; + import tests.io.MockOs; -import static libcore.io.OsConstants.*; + +import static android.system.OsConstants.*; public class SocketChannelTest extends junit.framework.TestCase { + private final MockOs mockOs = new MockOs(); - @Override public void setUp() throws Exception { + @Override + public void setUp() throws Exception { mockOs.install(); } - @Override protected void tearDown() throws Exception { + @Override + protected void tearDown() throws Exception { mockOs.uninstall(); } @@ -61,6 +72,7 @@ public class SocketChannelTest extends junit.framework.TestCase { } } + // https://code.google.com/p/android/issues/detail?id=56684 public void test_56684() throws Exception { mockOs.enqueueFault("connect", ENETUNREACH); @@ -78,7 +90,188 @@ public class SocketChannelTest extends junit.framework.TestCase { try { sc.finishConnect(); + fail(); } catch (ClosedChannelException expected) { } } + + /** Checks that closing a Socket's output stream also closes the Socket and SocketChannel. */ + public void test_channelSocketOutputStreamClosureState() throws Exception { + ServerSocket ss = new ServerSocket(0); + + SocketChannel sc = SocketChannel.open(ss.getLocalSocketAddress()); + sc.configureBlocking(true); + + Socket scSocket = sc.socket(); + OutputStream os = scSocket.getOutputStream(); + + assertTrue(sc.isOpen()); + assertFalse(scSocket.isClosed()); + + os.close(); + + assertFalse(sc.isOpen()); + assertTrue(scSocket.isClosed()); + + ss.close(); + } + + /** Checks that closing a Socket's input stream also closes the Socket and SocketChannel. */ + public void test_channelSocketInputStreamClosureState() throws Exception { + ServerSocket ss = new ServerSocket(0); + + SocketChannel sc = SocketChannel.open(ss.getLocalSocketAddress()); + sc.configureBlocking(true); + + Socket scSocket = sc.socket(); + InputStream is = scSocket.getInputStream(); + + assertTrue(sc.isOpen()); + assertFalse(scSocket.isClosed()); + + is.close(); + + assertFalse(sc.isOpen()); + assertTrue(scSocket.isClosed()); + + ss.close(); + } + + /** Checks the state of the SocketChannel and associated Socket after open() */ + public void test_open_initialState() throws Exception { + SocketChannel sc = SocketChannel.open(); + try { + assertNull(sc.socket().getLocalSocketAddress()); + + Socket socket = sc.socket(); + assertFalse(socket.isBound()); + assertFalse(socket.isClosed()); + assertFalse(socket.isConnected()); + assertEquals(-1, socket.getLocalPort()); + assertTrue(socket.getLocalAddress().isAnyLocalAddress()); + assertNull(socket.getLocalSocketAddress()); + assertNull(socket.getInetAddress()); + assertEquals(0, socket.getPort()); + assertNull(socket.getRemoteSocketAddress()); + assertFalse(socket.getReuseAddress()); + + assertSame(sc, socket.getChannel()); + } finally { + sc.close(); + } + } + + public void test_bind_unresolvedAddress() throws IOException { + SocketChannel sc = SocketChannel.open(); + try { + sc.socket().bind(new InetSocketAddress("unresolvedname", 31415)); + fail(); + } catch (IOException expected) { + } + + assertNull(sc.socket().getLocalSocketAddress()); + assertTrue(sc.isOpen()); + assertFalse(sc.isConnected()); + + sc.close(); + } + + /** Checks that the SocketChannel and associated Socket agree on the socket state. */ + public void test_bind_socketStateSync() throws IOException { + SocketChannel sc = SocketChannel.open(); + assertNull(sc.socket().getLocalSocketAddress()); + + Socket socket = sc.socket(); + assertNull(socket.getLocalSocketAddress()); + assertFalse(socket.isBound()); + + InetSocketAddress bindAddr = new InetSocketAddress("localhost", 0); + sc.socket().bind(bindAddr); + + InetSocketAddress actualAddr = (InetSocketAddress) sc.socket().getLocalSocketAddress(); + assertEquals(actualAddr, socket.getLocalSocketAddress()); + assertEquals(bindAddr.getHostName(), actualAddr.getHostName()); + assertTrue(socket.isBound()); + assertFalse(socket.isConnected()); + assertFalse(socket.isClosed()); + + sc.close(); + + assertFalse(sc.isOpen()); + assertTrue(socket.isClosed()); + } + + /** + * Checks that the SocketChannel and associated Socket agree on the socket state, even if + * the Socket object is requested/created after bind(). + */ + public void test_bind_socketObjectCreationAfterBind() throws IOException { + SocketChannel sc = SocketChannel.open(); + assertNull(sc.socket().getLocalSocketAddress()); + + InetSocketAddress bindAddr = new InetSocketAddress("localhost", 0); + sc.socket().bind(bindAddr); + + // Socket object creation after bind(). + Socket socket = sc.socket(); + InetSocketAddress actualAddr = (InetSocketAddress) sc.socket().getLocalSocketAddress(); + assertEquals(actualAddr, socket.getLocalSocketAddress()); + assertEquals(bindAddr.getHostName(), actualAddr.getHostName()); + assertTrue(socket.isBound()); + assertFalse(socket.isConnected()); + assertFalse(socket.isClosed()); + + sc.close(); + + assertFalse(sc.isOpen()); + assertTrue(socket.isClosed()); + } + + /** + * Tests connect() and object state for a blocking SocketChannel. Blocking mode is the default. + */ + public void test_connect_blocking() throws Exception { + ServerSocket ss = new ServerSocket(0); + + SocketChannel sc = SocketChannel.open(); + assertTrue(sc.isBlocking()); + + assertTrue(sc.connect(ss.getLocalSocketAddress())); + + assertTrue(sc.socket().isBound()); + assertTrue(sc.isConnected()); + assertTrue(sc.socket().isConnected()); + assertFalse(sc.socket().isClosed()); + assertTrue(sc.isBlocking()); + + ss.close(); + sc.close(); + } + + /** Tests connect() and object state for a non-blocking SocketChannel. */ + public void test_connect_nonBlocking() throws Exception { + ServerSocket ss = new ServerSocket(0); + + SocketChannel sc = SocketChannel.open(); + assertTrue(sc.isBlocking()); + sc.configureBlocking(false); + assertFalse(sc.isBlocking()); + + if (!sc.connect(ss.getLocalSocketAddress())) { + do { + assertTrue(sc.socket().isBound()); + assertFalse(sc.isConnected()); + assertFalse(sc.socket().isConnected()); + assertFalse(sc.socket().isClosed()); + } while (!sc.finishConnect()); + } + assertTrue(sc.socket().isBound()); + assertTrue(sc.isConnected()); + assertTrue(sc.socket().isConnected()); + assertFalse(sc.socket().isClosed()); + assertFalse(sc.isBlocking()); + + ss.close(); + sc.close(); + } } diff --git a/luni/src/test/java/libcore/java/security/KeyPairGeneratorTest.java b/luni/src/test/java/libcore/java/security/KeyPairGeneratorTest.java index d0b46ed..e7fdb1f 100644 --- a/luni/src/test/java/libcore/java/security/KeyPairGeneratorTest.java +++ b/luni/src/test/java/libcore/java/security/KeyPairGeneratorTest.java @@ -47,65 +47,120 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; +import javax.crypto.interfaces.DHPrivateKey; +import javax.crypto.interfaces.DHPublicKey; import javax.crypto.spec.DHParameterSpec; import junit.framework.TestCase; public class KeyPairGeneratorTest extends TestCase { - public void test_getInstance() throws Exception { + public void test_providerCount() { Provider[] providers = Security.getProviders(); - for (Provider provider : providers) { - Set<Provider.Service> services = provider.getServices(); - for (Provider.Service service : services) { - String type = service.getType(); - if (!type.equals("KeyPairGenerator")) { - continue; - } - String algorithm = service.getAlgorithm(); + // We expect there to be at least one provider. + assertTrue(providers.length > 0); + // If this fails remember to add _provider methods below. This test is sharded because it + // takes a long time to execute. + assertTrue(providers.length < 10); + } - // AndroidKeyStore is tested in CTS. - if ("AndroidKeyStore".equals(provider.getName())) { - continue; - } + public void test_getInstance_provider0() throws Exception { + test_getInstance(0); + } - AlgorithmParameterSpec params = null; + public void test_getInstance_provider1() throws Exception { + test_getInstance(1); + } - // TODO: detect if we're running in vogar and run the full test - if ("DH".equals(algorithm)) { - params = getDHParams(); - } + public void test_getInstance_provider2() throws Exception { + test_getInstance(2); + } - try { - // KeyPairGenerator.getInstance(String) - KeyPairGenerator kpg1 = KeyPairGenerator.getInstance(algorithm); - assertEquals(algorithm, kpg1.getAlgorithm()); - if (params != null) { - kpg1.initialize(params); - } - test_KeyPairGenerator(kpg1); - - // KeyPairGenerator.getInstance(String, Provider) - KeyPairGenerator kpg2 = KeyPairGenerator.getInstance(algorithm, provider); - assertEquals(algorithm, kpg2.getAlgorithm()); - assertEquals(provider, kpg2.getProvider()); - if (params != null) { - kpg2.initialize(params); - } - test_KeyPairGenerator(kpg2); - - // KeyPairGenerator.getInstance(String, String) - KeyPairGenerator kpg3 = KeyPairGenerator.getInstance(algorithm, - provider.getName()); - assertEquals(algorithm, kpg3.getAlgorithm()); - assertEquals(provider, kpg3.getProvider()); - if (params != null) { - kpg3.initialize(params); - } - test_KeyPairGenerator(kpg3); - } catch (Exception e) { - throw new Exception("Problem testing KeyPairGenerator." + algorithm, e); + public void test_getInstance_provider3() throws Exception { + test_getInstance(3); + } + + public void test_getInstance_provider4() throws Exception { + test_getInstance(4); + } + + public void test_getInstance_provider5() throws Exception { + test_getInstance(5); + } + + public void test_getInstance_provider6() throws Exception { + test_getInstance(6); + } + + public void test_getInstance_provider7() throws Exception { + test_getInstance(7); + } + + public void test_getInstance_provider8() throws Exception { + test_getInstance(8); + } + + public void test_getInstance_provider9() throws Exception { + test_getInstance(9); + } + + private void test_getInstance(int providerIndex) throws Exception { + Provider[] providers = Security.getProviders(); + if (providerIndex >= providers.length) { + // Providers can be added by vendors and other tests. We do not + // specify a fixed number and silenty pass if the provider at the + // specified index does not exist. + return; + } + Provider provider = providers[providerIndex]; + Set<Provider.Service> services = provider.getServices(); + for (Provider.Service service : services) { + String type = service.getType(); + if (!type.equals("KeyPairGenerator")) { + continue; + } + String algorithm = service.getAlgorithm(); + + // AndroidKeyStore is tested in CTS. + if ("AndroidKeyStore".equals(provider.getName())) { + continue; + } + + AlgorithmParameterSpec params = null; + + if ("DH".equals(algorithm)) { + params = getDHParams(); + } + + try { + // KeyPairGenerator.getInstance(String) + KeyPairGenerator kpg1 = KeyPairGenerator.getInstance(algorithm); + assertEquals(algorithm, kpg1.getAlgorithm()); + if (params != null) { + kpg1.initialize(params); } + test_KeyPairGenerator(kpg1); + + // KeyPairGenerator.getInstance(String, Provider) + KeyPairGenerator kpg2 = KeyPairGenerator.getInstance(algorithm, provider); + assertEquals(algorithm, kpg2.getAlgorithm()); + assertEquals(provider, kpg2.getProvider()); + if (params != null) { + kpg2.initialize(params); + } + test_KeyPairGenerator(kpg2); + + // KeyPairGenerator.getInstance(String, String) + KeyPairGenerator kpg3 = KeyPairGenerator.getInstance(algorithm, + provider.getName()); + assertEquals(algorithm, kpg3.getAlgorithm()); + assertEquals(provider, kpg3.getProvider()); + if (params != null) { + kpg3.initialize(params); + } + test_KeyPairGenerator(kpg3); + } catch (Exception e) { + throw new Exception("Problem testing KeyPairGenerator." + algorithm, e); } } } @@ -161,6 +216,14 @@ public class KeyPairGeneratorTest extends TestCase { test_KeyPair(kpg, kpg.generateKeyPair()); String algorithm = kpg.getAlgorithm(); + + // TODO: detect if we're running in vogar and run the full test + if ("DH".equals(algorithm)) { + // Disabled because this takes too long on devices. + // TODO: Re-enable DH test. http://b/5513723. + return; + } + List<Integer> keySizes = getKeySizes(algorithm); for (int keySize : keySizes) { kpg.initialize(keySize); @@ -206,6 +269,17 @@ public class KeyPairGeneratorTest extends TestCase { expectedAlgorithm = "DH"; } assertEquals(expectedAlgorithm, k.getAlgorithm().toUpperCase()); + if (expectedAlgorithm.equals("DH")) { + if (k instanceof DHPublicKey) { + DHPublicKey dhPub = (DHPublicKey) k; + assertEquals(dhPub.getParams().getP(), getDHParams().getP()); + } else if (k instanceof DHPrivateKey) { + DHPrivateKey dhPriv = (DHPrivateKey) k; + assertEquals(dhPriv.getParams().getP(), getDHParams().getP()); + } else { + fail("not a public or private key!?"); + } + } assertNotNull(k.getEncoded()); assertNotNull(k.getFormat()); @@ -287,7 +361,7 @@ public class KeyPairGeneratorTest extends TestCase { * * openssl gendh 512 | openssl dhparams -C */ - private static AlgorithmParameterSpec getDHParams() { + private static DHParameterSpec getDHParams() { BigInteger p = new BigInteger("E7AB1768BD75CD24700960FFA32D3F1557344E587101237532CC641646ED7A7C104743377F6D46251698B665CE2A6CBAB6714C2569A7D2CA22C0CF03FA40AC93", 16); BigInteger g = new BigInteger("02", 16); return new DHParameterSpec(p, g, 512); @@ -341,8 +415,6 @@ public class KeyPairGeneratorTest extends TestCase { public void testDSAGeneratorWithParams() throws Exception { final DSAParameterSpec dsaSpec = new DSAParameterSpec(DSA_P, DSA_Q, DSA_G); - boolean failure = false; - final Provider[] providers = Security.getProviders(); for (final Provider p : providers) { Service s = p.getService("KeyPairGenerator", "DSA"); diff --git a/luni/src/test/java/libcore/java/security/KeyStoreTest.java b/luni/src/test/java/libcore/java/security/KeyStoreTest.java index 47aa72a..9185ea8 100644 --- a/luni/src/test/java/libcore/java/security/KeyStoreTest.java +++ b/luni/src/test/java/libcore/java/security/KeyStoreTest.java @@ -46,6 +46,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.Enumeration; +import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -55,11 +56,17 @@ import junit.framework.TestCase; public class KeyStoreTest extends TestCase { - private static PrivateKeyEntry PRIVATE_KEY; - private static PrivateKeyEntry PRIVATE_KEY_2; + private static final HashMap<String, PrivateKeyEntry> sPrivateKeys + = new HashMap<String, PrivateKeyEntry>(); - private static SecretKey SECRET_KEY; - private static SecretKey SECRET_KEY_2; + private static TestKeyStore sTestKeyStore; + + private static final String[] KEY_TYPES = new String[] { "DH", "DSA", "RSA", "EC" }; + + private static PrivateKeyEntry sPrivateKey2; + + private static SecretKey sSecretKey; + private static SecretKey sSecretKey2; private static final String ALIAS_PRIVATE = "private"; private static final String ALIAS_CERTIFICATE = "certificate"; @@ -87,31 +94,56 @@ public class KeyStoreTest extends TestCase { private static final ProtectionParameter PARAM_BAD = new PasswordProtection(PASSWORD_BAD); private static PrivateKeyEntry getPrivateKey() { - if (PRIVATE_KEY == null) { - PRIVATE_KEY = TestKeyStore.getServer().getPrivateKey("RSA", "RSA"); + return getPrivateKey("RSA"); + } + + private static PrivateKeyEntry getPrivateKey(String keyType) { + // Avoiding initialization of TestKeyStore in the static initializer: it breaks CTS tests + // by causing a NetworkOnMainThreadException. + if (sTestKeyStore == null) { + sTestKeyStore = new TestKeyStore.Builder() + .keyAlgorithms("RSA", "DH_RSA", "DSA", "EC") + .aliasPrefix("rsa-dsa-ec-dh") + .build(); + } + + PrivateKeyEntry entry = sPrivateKeys.get(keyType); + if (entry == null) { + if ("RSA".equals(keyType)) { + entry = sTestKeyStore.getPrivateKey("RSA", "RSA"); + } else if ("DH".equals(keyType)) { + entry = sTestKeyStore.getPrivateKey("DH", "RSA"); + } else if ("DSA".equals(keyType)) { + entry = sTestKeyStore.getPrivateKey("DSA", "DSA"); + } else if ("EC".equals(keyType)) { + entry = sTestKeyStore.getPrivateKey("EC", "EC"); + } else { + throw new IllegalArgumentException("Unexpected key type " + keyType); + } + sPrivateKeys.put(keyType, entry); } - return PRIVATE_KEY; + return entry; } private static PrivateKeyEntry getPrivateKey2() { - if (PRIVATE_KEY_2 == null) { - PRIVATE_KEY_2 = TestKeyStore.getClientCertificate().getPrivateKey("RSA", "RSA"); + if (sPrivateKey2 == null) { + sPrivateKey2 = TestKeyStore.getClientCertificate().getPrivateKey("RSA", "RSA"); } - return PRIVATE_KEY_2; + return sPrivateKey2; } private static SecretKey getSecretKey() { - if (SECRET_KEY == null) { - SECRET_KEY = generateSecretKey(); + if (sSecretKey == null) { + sSecretKey = generateSecretKey(); } - return SECRET_KEY; + return sSecretKey; } private static SecretKey getSecretKey2() { - if (SECRET_KEY_2 == null) { - SECRET_KEY_2 = generateSecretKey(); + if (sSecretKey2 == null) { + sSecretKey2 = generateSecretKey(); } - return SECRET_KEY_2; + return sSecretKey2; } private static SecretKey generateSecretKey() { @@ -341,10 +373,15 @@ public class KeyStoreTest extends TestCase { ks.setCertificateEntry(alias, certificate); } + public static void assertPrivateKey(Key actual) throws Exception { assertEquals(getPrivateKey().getPrivateKey(), actual); } + public static void assertPrivateKey(String keyType, Key actual) + throws Exception { + assertEquals(getPrivateKey(keyType).getPrivateKey(), actual); + } public static void assertPrivateKey2(Key actual) throws Exception { assertEquals(getPrivateKey2().getPrivateKey(), actual); @@ -2183,8 +2220,10 @@ public class KeyStoreTest extends TestCase { continue; } if (isNullPasswordAllowed(keyStore) || isKeyPasswordIgnored(keyStore)) { - keyStore.setEntry(ALIAS_PRIVATE, getPrivateKey(), null); - assertPrivateKey(keyStore.getKey(ALIAS_PRIVATE, null)); + for (String keyType : KEY_TYPES) { + keyStore.setEntry(ALIAS_PRIVATE, getPrivateKey(keyType), null); + assertPrivateKey(keyType, keyStore.getKey(ALIAS_PRIVATE, null)); + } } else { try { keyStore.setEntry(ALIAS_PRIVATE, getPrivateKey(), null); diff --git a/luni/src/test/java/libcore/java/security/MessageDigestTest.java b/luni/src/test/java/libcore/java/security/MessageDigestTest.java index 3646a7a..ad410e4 100644 --- a/luni/src/test/java/libcore/java/security/MessageDigestTest.java +++ b/luni/src/test/java/libcore/java/security/MessageDigestTest.java @@ -24,6 +24,11 @@ import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Set; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; import junit.framework.TestCase; public final class MessageDigestTest extends TestCase { @@ -116,6 +121,12 @@ public final class MessageDigestTest extends TestCase { new byte[] { -38, 57, -93, -18, 94, 107, 75, 13, 50, 85, -65, -17, -107, 96, 24, -112, -81, -40, 7, 9}); + putExpectation("SHA-224", + INPUT_EMPTY, + new byte[] { -47, 74, 2, -116, 42, 58, 43, -55, 71, + 97, 2, -69, 40, -126, 52, -60, 21, + -94, -80, 31, -126, -114, -90, 42, + -59, -77, -28, 47}); putExpectation("SHA-256", INPUT_EMPTY, new byte[] { -29, -80, -60, 66, -104, -4, 28, 20, @@ -163,6 +174,12 @@ public final class MessageDigestTest extends TestCase { new byte[] { 123, -111, -37, -36, 86, -59, 120, 30, -33, 108, -120, 71, -76, -86, 105, 101, 86, 108, 92, 117 }); + putExpectation("SHA-224", + INPUT_256MB, + new byte[] { -78, 82, 5, -71, 57, 119, 77, -32, + -62, -74, -40, 64, -57, 79, 40, 116, + -18, 48, -69, 45, 18, -94, 111, 114, + -45, -93, 43, -11 }); putExpectation("SHA-256", INPUT_256MB, new byte[] { -90, -41, 42, -57, 105, 15, 83, -66, @@ -227,4 +244,33 @@ public final class MessageDigestTest extends TestCase { return buf.toString(); } + private final int THREAD_COUNT = 10; + + public void testMessageDigest_MultipleThreads_Misuse() throws Exception { + ExecutorService es = Executors.newFixedThreadPool(THREAD_COUNT); + + final CountDownLatch latch = new CountDownLatch(THREAD_COUNT); + final MessageDigest md = MessageDigest.getInstance("SHA-256"); + final byte[] message = new byte[64]; + + for (int i = 0; i < THREAD_COUNT; i++) { + es.submit(new Callable<Void>() { + @Override + public Void call() throws Exception { + // Try to make sure all the threads are ready first. + latch.countDown(); + latch.await(); + + for (int j = 0; j < 100; j++) { + md.update(message); + md.digest(); + } + + return null; + } + }); + } + es.shutdown(); + assertTrue("Test should not timeout", es.awaitTermination(1, TimeUnit.MINUTES)); + } } diff --git a/luni/src/test/java/libcore/java/security/MockPrivateKey.java b/luni/src/test/java/libcore/java/security/MockPrivateKey.java new file mode 100644 index 0000000..e5ac797 --- /dev/null +++ b/luni/src/test/java/libcore/java/security/MockPrivateKey.java @@ -0,0 +1,40 @@ +/* + * Copyright 2014 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.security; + +import java.security.PrivateKey; + +/** + * A mock PrivateKey class used for testing. + */ +@SuppressWarnings("serial") +public class MockPrivateKey implements PrivateKey { + @Override + public String getAlgorithm() { + throw new UnsupportedOperationException("not implemented"); + } + + @Override + public String getFormat() { + return "MOCK"; + } + + @Override + public byte[] getEncoded() { + throw new UnsupportedOperationException("not implemented"); + } +} diff --git a/luni/src/test/java/libcore/java/security/MockPrivateKey2.java b/luni/src/test/java/libcore/java/security/MockPrivateKey2.java new file mode 100644 index 0000000..a1c02c9 --- /dev/null +++ b/luni/src/test/java/libcore/java/security/MockPrivateKey2.java @@ -0,0 +1,40 @@ +/* + * Copyright 2014 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.security; + +import java.security.PrivateKey; + +/** + * A mock PrivateKey class used for testing. + */ +@SuppressWarnings("serial") +public class MockPrivateKey2 implements PrivateKey { + @Override + public String getAlgorithm() { + throw new UnsupportedOperationException("not implemented"); + } + + @Override + public String getFormat() { + return "MOCK"; + } + + @Override + public byte[] getEncoded() { + throw new UnsupportedOperationException("not implemented"); + } +} diff --git a/luni/src/test/java/libcore/java/security/MockPublicKey.java b/luni/src/test/java/libcore/java/security/MockPublicKey.java new file mode 100644 index 0000000..130b461 --- /dev/null +++ b/luni/src/test/java/libcore/java/security/MockPublicKey.java @@ -0,0 +1,40 @@ +/* + * Copyright 2014 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.security; + +import java.security.PublicKey; + +/** + * A mock PublicKey class used for testing. + */ +@SuppressWarnings("serial") +public class MockPublicKey implements PublicKey { + @Override + public String getAlgorithm() { + throw new UnsupportedOperationException("not implemented"); + } + + @Override + public String getFormat() { + return "MOCK"; + } + + @Override + public byte[] getEncoded() { + throw new UnsupportedOperationException("not implemented"); + } +} diff --git a/luni/src/test/java/libcore/java/security/MockSignatureSpi.java b/luni/src/test/java/libcore/java/security/MockSignatureSpi.java new file mode 100644 index 0000000..6017547 --- /dev/null +++ b/luni/src/test/java/libcore/java/security/MockSignatureSpi.java @@ -0,0 +1,118 @@ +/* + * Copyright 2014 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.security; + +import java.security.InvalidKeyException; +import java.security.InvalidParameterException; +import java.security.Key; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.SignatureException; +import java.security.SignatureSpi; + +/** + * Mock SignatureSpi used by {@link SignatureTest}. + */ +public class MockSignatureSpi extends SignatureSpi { + public static class SpecificKeyTypes extends MockSignatureSpi { + @Override + public void checkKeyType(Key key) throws InvalidKeyException { + if (!(key instanceof MockPrivateKey)) { + throw new InvalidKeyException("Must be MockPrivateKey!"); + } + } + } + + public static class SpecificKeyTypes2 extends MockSignatureSpi { + @Override + public void checkKeyType(Key key) throws InvalidKeyException { + if (!(key instanceof MockPrivateKey2)) { + throw new InvalidKeyException("Must be MockPrivateKey2!"); + } + } + } + + public static class AllKeyTypes extends MockSignatureSpi { + } + + public void checkKeyType(Key key) throws InvalidKeyException { + } + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineInitVerify(java.security.PublicKey) + */ + @Override + protected void engineInitVerify(PublicKey publicKey) throws InvalidKeyException { + throw new UnsupportedOperationException("not implemented"); + } + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineInitSign(java.security.PrivateKey) + */ + @Override + protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException { + checkKeyType(privateKey); + } + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineUpdate(byte) + */ + @Override + protected void engineUpdate(byte b) throws SignatureException { + throw new UnsupportedOperationException("not implemented"); + } + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineSign() + */ + @Override + protected byte[] engineSign() throws SignatureException { + throw new UnsupportedOperationException("not implemented"); + } + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineVerify(byte[]) + */ + @Override + protected boolean engineVerify(byte[] sigBytes) throws SignatureException { + throw new UnsupportedOperationException("not implemented"); + } + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineSetParameter(java.lang.String, java.lang.Object) + */ + @Override + protected void engineSetParameter(String param, Object value) throws InvalidParameterException { + throw new UnsupportedOperationException("not implemented"); + } + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineGetParameter(java.lang.String) + */ + @Override + protected Object engineGetParameter(String param) throws InvalidParameterException { + throw new UnsupportedOperationException("not implemented"); + } + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineUpdate(byte[], int, int) + */ + @Override + protected void engineUpdate(byte[] b, int off, int len) throws SignatureException { + throw new UnsupportedOperationException("not implemented"); + } +} diff --git a/luni/src/test/java/libcore/java/security/OldDHTest.java b/luni/src/test/java/libcore/java/security/OldDHTest.java index 421d153..58d96ed 100644 --- a/luni/src/test/java/libcore/java/security/OldDHTest.java +++ b/luni/src/test/java/libcore/java/security/OldDHTest.java @@ -15,7 +15,6 @@ */ package libcore.java.security; -import dalvik.annotation.BrokenTest; import java.security.AlgorithmParameterGenerator; import java.security.AlgorithmParameters; import java.security.KeyPair; @@ -27,7 +26,7 @@ import junit.framework.TestCase; public class OldDHTest extends TestCase { - @BrokenTest("Suffers from DH slowness, disabling for now") + // BrokenTest Suffers from DH slowness, disabling for now public void testDHGen() throws Exception { KeyPairGenerator gen = null; try { diff --git a/luni/src/test/java/libcore/java/security/OldKeyPairGeneratorTestDH.java b/luni/src/test/java/libcore/java/security/OldKeyPairGeneratorTestDH.java index f39705b..9be282d 100644 --- a/luni/src/test/java/libcore/java/security/OldKeyPairGeneratorTestDH.java +++ b/luni/src/test/java/libcore/java/security/OldKeyPairGeneratorTestDH.java @@ -15,7 +15,6 @@ */ package libcore.java.security; -import dalvik.annotation.BrokenTest; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; @@ -24,7 +23,7 @@ import tests.security.KeyAgreementHelper; public class OldKeyPairGeneratorTestDH extends TestCase { - @BrokenTest("Takes ages due to DH computations. Disabling for now.") + // Broken Test: Takes ages due to DH computations. Disabling for now. public void testKeyPairGenerator() throws NoSuchAlgorithmException { KeyPairGenerator generator = KeyPairGenerator.getInstance("DH"); diff --git a/luni/src/test/java/libcore/java/security/ProviderTest.java b/luni/src/test/java/libcore/java/security/ProviderTest.java index 97a80a9..994214b 100644 --- a/luni/src/test/java/libcore/java/security/ProviderTest.java +++ b/luni/src/test/java/libcore/java/security/ProviderTest.java @@ -16,27 +16,40 @@ package libcore.java.security; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidParameterException; +import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.SecureRandom; import java.security.SecureRandomSpi; import java.security.Security; -import java.security.Provider; -import java.security.SecureRandom; -import java.security.SecureRandomSpi; -import java.security.Security; +import java.security.cert.CRL; +import java.security.cert.CRLSelector; +import java.security.cert.CertSelector; +import java.security.cert.CertStoreException; +import java.security.cert.CertStoreParameters; +import java.security.cert.CertStoreSpi; +import java.security.cert.Certificate; +import java.security.interfaces.RSAPrivateKey; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; -import java.util.Map.Entry; import java.util.Map; +import java.util.Map.Entry; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; +import javax.crypto.Cipher; +import javax.crypto.NoSuchPaddingException; import junit.framework.TestCase; +import libcore.javax.crypto.MockKey; public class ProviderTest extends TestCase { + private static final boolean LOG_DEBUG = false; /** * Makes sure all all expected implementations (but not aliases) @@ -44,16 +57,15 @@ public class ProviderTest extends TestCase { * StandardNames */ public void test_Provider_getServices() throws Exception { - // build set of expected algorithms - Map<String,Set<String>> remaining + Map<String,Set<String>> remainingExpected = new HashMap<String,Set<String>>(StandardNames.PROVIDER_ALGORITHMS); - for (Entry<String,Set<String>> entry : remaining.entrySet()) { + for (Entry<String,Set<String>> entry : remainingExpected.entrySet()) { entry.setValue(new HashSet<String>(entry.getValue())); } - List<String> extra = new ArrayList(); - List<String> missing = new ArrayList(); + List<String> extra = new ArrayList<String>(); + List<String> missing = new ArrayList<String>(); Provider[] providers = Security.getProviders(); for (Provider provider : providers) { @@ -70,7 +82,7 @@ public class ProviderTest extends TestCase { String type = service.getType(); String algorithm = service.getAlgorithm().toUpperCase(); String className = service.getClassName(); - if (false) { + if (LOG_DEBUG) { System.out.println(providerName + " " + type + " " + algorithm @@ -78,8 +90,8 @@ public class ProviderTest extends TestCase { } // remove from remaining, assert unknown if missing - Set<String> algorithms = remaining.get(type); - if (algorithms == null || !algorithms.remove(algorithm)) { + Set<String> remainingAlgorithms = remainingExpected.get(type); + if (remainingAlgorithms == null || !remainingAlgorithms.remove(algorithm)) { // seems to be missing, but sometimes the same // algorithm is available from multiple providers // (e.g. KeyFactory RSA is available from @@ -89,9 +101,28 @@ public class ProviderTest extends TestCase { && StandardNames.PROVIDER_ALGORITHMS.get(type).contains(algorithm))) { extra.add("Unknown " + type + " " + algorithm + " " + providerName + "\n"); } + } else if ("Cipher".equals(type) && !algorithm.contains("/")) { + /* + * Cipher selection follows special rules where you can + * specify the mode and padding during the getInstance call. + * Try to see if the service supports this. + */ + Set<String> toRemove = new HashSet<String>(); + for (String remainingAlgo : remainingAlgorithms) { + String[] parts = remainingAlgo.split("/"); + if (parts.length == 3 && algorithm.equals(parts[0])) { + try { + Cipher.getInstance(remainingAlgo, provider); + toRemove.add(remainingAlgo); + } catch (NoSuchAlgorithmException ignored) { + } catch (NoSuchPaddingException ignored) { + } + } + } + remainingAlgorithms.removeAll(toRemove); } - if (algorithms != null && algorithms.isEmpty()) { - remaining.remove(type); + if (remainingAlgorithms != null && remainingAlgorithms.isEmpty()) { + remainingExpected.remove(type); } // make sure class exists and can be initialized @@ -113,7 +144,7 @@ public class ProviderTest extends TestCase { assertEquals("Extra algorithms", Collections.EMPTY_LIST, extra); // assert that we don't have any missing in the implementation - assertEquals("Missing algorithms", Collections.EMPTY_MAP, remaining); + assertEquals("Missing algorithms", Collections.EMPTY_MAP, remainingExpected); // assert that we don't have any missing classes Collections.sort(missing); // sort it for readability @@ -202,11 +233,356 @@ public class ProviderTest extends TestCase { } } + private static final String[] TYPES_SERVICES_CHECKED = new String[] { + "KeyFactory", "CertPathBuilder", "Cipher", "SecureRandom", + "AlgorithmParameterGenerator", "Signature", "KeyPairGenerator", "CertificateFactory", + "MessageDigest", "KeyAgreement", "CertStore", "SSLContext", "AlgorithmParameters", + "TrustManagerFactory", "KeyGenerator", "Mac", "CertPathValidator", "SecretKeyFactory", + "KeyManagerFactory", "KeyStore", + }; + + private static final HashSet<String> TYPES_SUPPORTS_PARAMETER = new HashSet<String>( + Arrays.asList(new String[] { + "Mac", "KeyAgreement", "Cipher", "Signature", + })); + + private static final HashSet<String> TYPES_NOT_SUPPORTS_PARAMETER = new HashSet<String>( + Arrays.asList(TYPES_SERVICES_CHECKED)); + static { + TYPES_NOT_SUPPORTS_PARAMETER.removeAll(TYPES_SUPPORTS_PARAMETER); + } + + public void test_Provider_getServices_supportsParameter() throws Exception { + HashSet<String> remainingTypes = new HashSet<String>(Arrays.asList(TYPES_SERVICES_CHECKED)); + + HashSet<String> supportsParameterTypes = new HashSet<String>(); + HashSet<String> noSupportsParameterTypes = new HashSet<String>(); + + Provider[] providers = Security.getProviders(); + for (Provider provider : providers) { + Set<Provider.Service> services = provider.getServices(); + assertNotNull(services); + assertFalse(services.isEmpty()); + + for (Provider.Service service : services) { + final String type = service.getType(); + remainingTypes.remove(type); + try { + service.supportsParameter(new MockKey()); + supportsParameterTypes.add(type); + } catch (InvalidParameterException e) { + noSupportsParameterTypes.add(type); + try { + service.supportsParameter(new Object()); + fail("Should throw on non-Key parameter"); + } catch (InvalidParameterException expected) { + } + } + } + } + + supportsParameterTypes.retainAll(TYPES_SUPPORTS_PARAMETER); + assertEquals("Types that should support parameters", TYPES_SUPPORTS_PARAMETER, + supportsParameterTypes); + + noSupportsParameterTypes.retainAll(TYPES_NOT_SUPPORTS_PARAMETER); + assertEquals("Types that should not support parameters", TYPES_NOT_SUPPORTS_PARAMETER, + noSupportsParameterTypes); + + assertEquals("Types that should be checked", Collections.EMPTY_SET, remainingTypes); + } + + public static class MockSpi { + public Object parameter; + + public MockSpi(MockKey parameter) { + this.parameter = parameter; + } + }; + + @SuppressWarnings("serial") + public void testProviderService_supportsParameter_UnknownService_Success() throws Exception { + Provider provider = new MockProvider("MockProvider") { + public void setup() { + put("Fake.FOO", MockSpi.class.getName()); + } + }; + + Security.addProvider(provider); + try { + Provider.Service service = provider.getService("Fake", "FOO"); + assertTrue(service.supportsParameter(new Object())); + } finally { + Security.removeProvider(provider.getName()); + } + } + + @SuppressWarnings("serial") + public void testProviderService_supportsParameter_KnownService_NoClassInitialization_Success() + throws Exception { + Provider provider = new MockProvider("MockProvider") { + public void setup() { + put("Signature.FOO", MockSpi.class.getName()); + put("Signature.FOO SupportedKeyClasses", getClass().getName() + + ".UninitializedMockKey"); + } + }; + + Security.addProvider(provider); + try { + Provider.Service service = provider.getService("Signature", "FOO"); + assertFalse(service.supportsParameter(new MockKey())); + } finally { + Security.removeProvider(provider.getName()); + } + } + + @SuppressWarnings("serial") + public static class UninitializedMockKey extends MockKey { + static { + fail("This should not be initialized"); + } + } + + @SuppressWarnings("serial") + public void testProviderService_supportsParameter_TypeDoesNotSupportParameter_Failure() + throws Exception { + Provider provider = new MockProvider("MockProvider") { + public void setup() { + put("KeyFactory.FOO", MockSpi.class.getName()); + } + }; + + Security.addProvider(provider); + try { + Provider.Service service = provider.getService("KeyFactory", "FOO"); + try { + service.supportsParameter(new MockKey()); + fail("Should always throw exception"); + } catch (InvalidParameterException expected) { + } + } finally { + Security.removeProvider(provider.getName()); + } + } + + @SuppressWarnings("serial") + public void testProviderService_supportsParameter_SupportedKeyClasses_NonKeyClass_Success() + throws Exception { + Provider provider = new MockProvider("MockProvider") { + public void setup() { + put("Signature.FOO", MockSpi.class.getName()); + put("Signature.FOO SupportedKeyClasses", MockSpi.class.getName()); + } + }; + + Security.addProvider(provider); + try { + Provider.Service service = provider.getService("Signature", "FOO"); + assertFalse(service.supportsParameter(new MockKey())); + } finally { + Security.removeProvider(provider.getName()); + } + } + + @SuppressWarnings("serial") + public void testProviderService_supportsParameter_KnownService_NonKey_Failure() + throws Exception { + Provider provider = new MockProvider("MockProvider") { + public void setup() { + put("Signature.FOO", MockSpi.class.getName()); + } + }; + + Security.addProvider(provider); + try { + Provider.Service service = provider.getService("Signature", "FOO"); + try { + service.supportsParameter(new Object()); + fail("Should throw when non-Key passed in"); + } catch (InvalidParameterException expected) { + } + } finally { + Security.removeProvider(provider.getName()); + } + } + + @SuppressWarnings("serial") + public void testProviderService_supportsParameter_KnownService_SupportedKeyClasses_NonKey_Failure() + throws Exception { + Provider provider = new MockProvider("MockProvider") { + public void setup() { + put("Signature.FOO", MockSpi.class.getName()); + put("Signature.FOO SupportedKeyClasses", RSAPrivateKey.class.getName()); + } + }; + + Security.addProvider(provider); + try { + Provider.Service service = provider.getService("Signature", "FOO"); + try { + service.supportsParameter(new Object()); + fail("Should throw on non-Key instance passed in"); + } catch (InvalidParameterException expected) { + } + } finally { + Security.removeProvider(provider.getName()); + } + } + + @SuppressWarnings("serial") + public void testProviderService_supportsParameter_KnownService_Null_Failure() throws Exception { + Provider provider = new MockProvider("MockProvider") { + public void setup() { + put("Signature.FOO", MockSpi.class.getName()); + put("Signature.FOO SupportedKeyClasses", RSAPrivateKey.class.getName()); + } + }; + + Security.addProvider(provider); + try { + Provider.Service service = provider.getService("Signature", "FOO"); + assertFalse(service.supportsParameter(null)); + } finally { + Security.removeProvider(provider.getName()); + } + } + + @SuppressWarnings("serial") + public void testProviderService_supportsParameter_SupportedKeyClasses_Success() + throws Exception { + Provider provider = new MockProvider("MockProvider") { + public void setup() { + put("Signature.FOO", MockSpi.class.getName()); + put("Signature.FOO SupportedKeyClasses", MockKey.class.getName()); + } + }; + + Security.addProvider(provider); + try { + Provider.Service service = provider.getService("Signature", "FOO"); + assertTrue(service.supportsParameter(new MockKey())); + } finally { + Security.removeProvider(provider.getName()); + } + } + + @SuppressWarnings("serial") + public void testProviderService_supportsParameter_SupportedKeyClasses_Failure() + throws Exception { + Provider provider = new MockProvider("MockProvider") { + public void setup() { + put("Signature.FOO", MockSpi.class.getName()); + put("Signature.FOO SupportedKeyClasses", RSAPrivateKey.class.getName()); + } + }; + + Security.addProvider(provider); + try { + Provider.Service service = provider.getService("Signature", "FOO"); + assertFalse(service.supportsParameter(new MockKey())); + } finally { + Security.removeProvider(provider.getName()); + } + } + + @SuppressWarnings("serial") + public void testProviderService_supportsParameter_SupportedKeyFormats_Success() + throws Exception { + Provider provider = new MockProvider("MockProvider") { + public void setup() { + put("Signature.FOO", MockSpi.class.getName()); + put("Signature.FOO SupportedKeyFormats", new MockKey().getFormat()); + } + }; + + Security.addProvider(provider); + try { + Provider.Service service = provider.getService("Signature", "FOO"); + assertTrue(service.supportsParameter(new MockKey())); + } finally { + Security.removeProvider(provider.getName()); + } + } + + @SuppressWarnings("serial") + public void testProviderService_supportsParameter_SupportedKeyFormats_Failure() + throws Exception { + Provider provider = new MockProvider("MockProvider") { + public void setup() { + put("Signature.FOO", MockSpi.class.getName()); + put("Signature.FOO SupportedKeyFormats", "Invalid"); + } + }; + + Security.addProvider(provider); + try { + Provider.Service service = provider.getService("Signature", "FOO"); + assertFalse(service.supportsParameter(new MockKey())); + } finally { + Security.removeProvider(provider.getName()); + } + } + + @SuppressWarnings("serial") + public void testProviderService_newInstance_DoesNotCallSupportsParameter_Success() + throws Exception { + MockProvider provider = new MockProvider("MockProvider"); + + provider.putServiceForTest(new Provider.Service(provider, "CertStore", "FOO", + MyCertStoreSpi.class.getName(), null, null) { + @Override + public boolean supportsParameter(Object parameter) { + fail("This should not be called"); + return false; + } + }); + + Security.addProvider(provider); + try { + Provider.Service service = provider.getService("CertStore", "FOO"); + assertNotNull(service.newInstance(new MyCertStoreParameters())); + } finally { + Security.removeProvider(provider.getName()); + } + } + + public static class MyCertStoreSpi extends CertStoreSpi { + public MyCertStoreSpi(CertStoreParameters params) throws InvalidAlgorithmParameterException { + super(params); + } + + @Override + public Collection<? extends Certificate> engineGetCertificates(CertSelector selector) + throws CertStoreException { + throw new UnsupportedOperationException(); + } + + @Override + public Collection<? extends CRL> engineGetCRLs(CRLSelector selector) + throws CertStoreException { + throw new UnsupportedOperationException(); + } + } + + public static class MyCertStoreParameters implements CertStoreParameters { + public Object clone() { + return new MyCertStoreParameters(); + } + } + /** * http://code.google.com/p/android/issues/detail?id=21449 */ public void testSecureRandomImplementationOrder() { - Provider srp = new SRProvider(); + @SuppressWarnings("serial") + Provider srp = new MockProvider("SRProvider") { + public void setup() { + put("SecureRandom.SecureRandom1", SecureRandom1.class.getName()); + put("SecureRandom.SecureRandom2", SecureRandom2.class.getName()); + put("SecureRandom.SecureRandom3", SecureRandom3.class.getName()); + } + }; try { int position = Security.insertProviderAt(srp, 1); // first is one, not zero assertEquals(1, position); @@ -219,16 +595,22 @@ public class ProviderTest extends TestCase { } } - public static class SRProvider extends Provider { + @SuppressWarnings("serial") + private static class MockProvider extends Provider { + public MockProvider(String name) { + super(name, 1.0, "Mock provider used for testing"); + setup(); + } + + public void setup() { + } - SRProvider() { - super("SRProvider", 1.42, "SecureRandom Provider"); - put("SecureRandom.SecureRandom1", SecureRandom1.class.getName()); - put("SecureRandom.SecureRandom2", SecureRandom2.class.getName()); - put("SecureRandom.SecureRandom3", SecureRandom3.class.getName()); + public void putServiceForTest(Provider.Service service) { + putService(service); } } + @SuppressWarnings("serial") public static abstract class AbstractSecureRandom extends SecureRandomSpi { protected void engineSetSeed(byte[] seed) { throw new UnsupportedOperationException(); @@ -241,8 +623,13 @@ public class ProviderTest extends TestCase { } } + @SuppressWarnings("serial") public static class SecureRandom1 extends AbstractSecureRandom {} + + @SuppressWarnings("serial") public static class SecureRandom2 extends AbstractSecureRandom {} + + @SuppressWarnings("serial") public static class SecureRandom3 extends AbstractSecureRandom {} } diff --git a/luni/src/test/java/libcore/java/security/SignatureTest.java b/luni/src/test/java/libcore/java/security/SignatureTest.java index 7f8b4f4..5e02f10 100644 --- a/luni/src/test/java/libcore/java/security/SignatureTest.java +++ b/luni/src/test/java/libcore/java/security/SignatureTest.java @@ -18,9 +18,11 @@ package libcore.java.security; import java.math.BigInteger; import java.security.InvalidKeyException; +import java.security.InvalidParameterException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; +import java.security.MessageDigest; import java.security.PrivateKey; import java.security.Provider; import java.security.PublicKey; @@ -38,10 +40,197 @@ import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Set; - +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; import junit.framework.TestCase; public class SignatureTest extends TestCase { + private static abstract class MockProvider extends Provider { + public MockProvider(String name) { + super(name, 1.0, "Mock provider used for testing"); + setup(); + } + + public abstract void setup(); + } + + public void testSignature_getInstance_SuppliedProviderNotRegistered_Success() throws Exception { + Provider mockProvider = new MockProvider("MockProvider") { + public void setup() { + put("Signature.FOO", MockSignatureSpi.AllKeyTypes.class.getName()); + } + }; + + { + Signature s = Signature.getInstance("FOO", mockProvider); + s.initSign(new MockPrivateKey()); + assertEquals(mockProvider, s.getProvider()); + } + } + + public void testSignature_getInstance_OnlyUsesSpecifiedProvider_SameNameAndClass_Success() + throws Exception { + Provider mockProvider = new MockProvider("MockProvider") { + public void setup() { + put("Signature.FOO", MockSignatureSpi.AllKeyTypes.class.getName()); + } + }; + + Security.addProvider(mockProvider); + try { + { + Provider mockProvider2 = new MockProvider("MockProvider") { + public void setup() { + put("Signature.FOO", MockSignatureSpi.AllKeyTypes.class.getName()); + } + }; + Signature s = Signature.getInstance("FOO", mockProvider2); + assertEquals(mockProvider2, s.getProvider()); + } + } finally { + Security.removeProvider(mockProvider.getName()); + } + } + + public void testSignature_getInstance_DelayedInitialization_KeyType() throws Exception { + Provider mockProviderSpecific = new MockProvider("MockProviderSpecific") { + public void setup() { + put("Signature.FOO", MockSignatureSpi.SpecificKeyTypes.class.getName()); + put("Signature.FOO SupportedKeyClasses", MockPrivateKey.class.getName()); + } + }; + Provider mockProviderSpecific2 = new MockProvider("MockProviderSpecific2") { + public void setup() { + put("Signature.FOO", MockSignatureSpi.SpecificKeyTypes2.class.getName()); + put("Signature.FOO SupportedKeyClasses", MockPrivateKey2.class.getName()); + } + }; + Provider mockProviderAll = new MockProvider("MockProviderAll") { + public void setup() { + put("Signature.FOO", MockSignatureSpi.AllKeyTypes.class.getName()); + } + }; + + Security.addProvider(mockProviderSpecific); + Security.addProvider(mockProviderSpecific2); + Security.addProvider(mockProviderAll); + + try { + { + Signature s = Signature.getInstance("FOO"); + s.initSign(new MockPrivateKey()); + assertEquals(mockProviderSpecific, s.getProvider()); + + try { + s.initSign(new MockPrivateKey2()); + assertEquals(mockProviderSpecific2, s.getProvider()); + if (StandardNames.IS_RI) { + fail("RI was broken before; fix tests now that it works!"); + } + } catch (InvalidKeyException e) { + if (!StandardNames.IS_RI) { + fail("Non-RI should select the right provider"); + } + } + } + + { + Signature s = Signature.getInstance("FOO"); + s.initSign(new PrivateKey() { + @Override + public String getAlgorithm() { + throw new UnsupportedOperationException("not implemented"); + } + + @Override + public String getFormat() { + throw new UnsupportedOperationException("not implemented"); + } + + @Override + public byte[] getEncoded() { + throw new UnsupportedOperationException("not implemented"); + } + }); + assertEquals(mockProviderAll, s.getProvider()); + } + + { + Signature s = Signature.getInstance("FOO"); + assertEquals(mockProviderSpecific, s.getProvider()); + } + } finally { + Security.removeProvider(mockProviderSpecific.getName()); + Security.removeProvider(mockProviderSpecific2.getName()); + Security.removeProvider(mockProviderAll.getName()); + } + } + + private static class MySignature extends Signature { + protected MySignature(String algorithm) { + super(algorithm); + } + + @Override + protected void engineInitVerify(PublicKey publicKey) throws InvalidKeyException { + throw new UnsupportedOperationException(); + } + + @Override + protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException { + throw new UnsupportedOperationException(); + } + + @Override + protected void engineUpdate(byte b) throws SignatureException { + throw new UnsupportedOperationException(); + } + + @Override + protected void engineUpdate(byte[] b, int off, int len) throws SignatureException { + throw new UnsupportedOperationException(); + } + + @Override + protected byte[] engineSign() throws SignatureException { + throw new UnsupportedOperationException(); + } + + @Override + protected boolean engineVerify(byte[] sigBytes) throws SignatureException { + throw new UnsupportedOperationException(); + } + + @Override + protected void engineSetParameter(String param, Object value) { + throw new UnsupportedOperationException(); + } + + @Override + protected Object engineGetParameter(String param) throws InvalidParameterException { + throw new UnsupportedOperationException(); + } + } + + public void testSignature_getProvider_Subclass() throws Exception { + Provider mockProviderNonSpi = new MockProvider("MockProviderNonSpi") { + public void setup() { + put("Signature.FOO", MySignature.class.getName()); + } + }; + + Security.addProvider(mockProviderNonSpi); + + try { + Signature s = new MySignature("FOO"); + assertNull(s.getProvider()); + } finally { + Security.removeProvider(mockProviderNonSpi.getName()); + } + } // 20 bytes for DSA private final byte[] DATA = new byte[20]; @@ -140,6 +329,8 @@ public class SignatureTest extends TestCase { // http://code.google.com/p/android/issues/detail?id=34933 sig.verify(signature); } + + testSignature_MultipleThreads_Misuse(sig); } private static final byte[] PK_BYTES = hexToBytes( @@ -425,6 +616,44 @@ public class SignatureTest extends TestCase { (byte) 0xc0, (byte) 0x09, (byte) 0x15, (byte) 0x7d, (byte) 0x8a, (byte) 0x21, (byte) 0xbc, (byte) 0xa3, }; + /* + * echo 'Android.' | openssl dgst -sha224 -binary -sign privkey.pem | recode ../x1 | sed 's/0x/(byte) 0x/g' + */ + private static final byte[] SHA224withRSA_Vector2Signature = new byte[] { + (byte) 0xBD, (byte) 0x3F, (byte) 0xD4, (byte) 0x20, (byte) 0x5B, (byte) 0xC0, (byte) 0x89, (byte) 0x4F, + (byte) 0x99, (byte) 0x6C, (byte) 0xF4, (byte) 0xA4, (byte) 0x70, (byte) 0xE3, (byte) 0x5B, (byte) 0x33, + (byte) 0xB3, (byte) 0xCA, (byte) 0xFE, (byte) 0x1F, (byte) 0xB9, (byte) 0x3A, (byte) 0xD6, (byte) 0x9B, + (byte) 0x1E, (byte) 0xDA, (byte) 0x65, (byte) 0x06, (byte) 0xBD, (byte) 0xC3, (byte) 0x2B, (byte) 0xF8, + (byte) 0x0E, (byte) 0xA0, (byte) 0xB5, (byte) 0x33, (byte) 0x7F, (byte) 0x15, (byte) 0xDC, (byte) 0xBB, + (byte) 0xDC, (byte) 0x98, (byte) 0x96, (byte) 0xF5, (byte) 0xF8, (byte) 0xE5, (byte) 0x55, (byte) 0x7D, + (byte) 0x48, (byte) 0x51, (byte) 0xC5, (byte) 0xAE, (byte) 0x12, (byte) 0xA2, (byte) 0x61, (byte) 0xC7, + (byte) 0xA2, (byte) 0x00, (byte) 0x0F, (byte) 0x35, (byte) 0x54, (byte) 0x3C, (byte) 0x7E, (byte) 0x97, + (byte) 0x19, (byte) 0x2D, (byte) 0x8F, (byte) 0xFD, (byte) 0x51, (byte) 0x04, (byte) 0x72, (byte) 0x23, + (byte) 0x65, (byte) 0x16, (byte) 0x41, (byte) 0x12, (byte) 0x46, (byte) 0xD6, (byte) 0x20, (byte) 0xB6, + (byte) 0x4E, (byte) 0xD6, (byte) 0xE8, (byte) 0x60, (byte) 0x91, (byte) 0x05, (byte) 0xCA, (byte) 0x57, + (byte) 0x6F, (byte) 0x53, (byte) 0xA4, (byte) 0x05, (byte) 0x2A, (byte) 0x37, (byte) 0xDD, (byte) 0x2E, + (byte) 0xA4, (byte) 0xC7, (byte) 0xBF, (byte) 0x9E, (byte) 0xF6, (byte) 0xD5, (byte) 0xD4, (byte) 0x34, + (byte) 0xB8, (byte) 0xB3, (byte) 0x8B, (byte) 0x66, (byte) 0x2C, (byte) 0xB6, (byte) 0x5F, (byte) 0xA4, + (byte) 0xB7, (byte) 0x77, (byte) 0xF8, (byte) 0x9A, (byte) 0x9C, (byte) 0x44, (byte) 0x9F, (byte) 0xF0, + (byte) 0xCA, (byte) 0x53, (byte) 0x56, (byte) 0x2F, (byte) 0x99, (byte) 0x2E, (byte) 0x4B, (byte) 0xA2, + (byte) 0x26, (byte) 0x50, (byte) 0x30, (byte) 0x97, (byte) 0x2B, (byte) 0x4B, (byte) 0x0C, (byte) 0x3E, + (byte) 0x28, (byte) 0x0B, (byte) 0x88, (byte) 0x87, (byte) 0x9E, (byte) 0xCE, (byte) 0xCB, (byte) 0x57, + (byte) 0x72, (byte) 0x6B, (byte) 0xF6, (byte) 0xD6, (byte) 0xAA, (byte) 0x4D, (byte) 0x5F, (byte) 0x19, + (byte) 0x7A, (byte) 0xAD, (byte) 0x44, (byte) 0x09, (byte) 0x33, (byte) 0x62, (byte) 0xC8, (byte) 0x56, + (byte) 0x82, (byte) 0x84, (byte) 0xBF, (byte) 0x52, (byte) 0xC6, (byte) 0xA2, (byte) 0x2B, (byte) 0xE3, + (byte) 0xC2, (byte) 0x7F, (byte) 0xE3, (byte) 0x06, (byte) 0xC3, (byte) 0x30, (byte) 0xB8, (byte) 0xD4, + (byte) 0x01, (byte) 0xE6, (byte) 0x3D, (byte) 0xDB, (byte) 0xCA, (byte) 0xE4, (byte) 0xFB, (byte) 0xA8, + (byte) 0x7B, (byte) 0x2D, (byte) 0x8F, (byte) 0x39, (byte) 0x7A, (byte) 0x63, (byte) 0x9F, (byte) 0x02, + (byte) 0xE8, (byte) 0x91, (byte) 0xD1, (byte) 0xEE, (byte) 0x60, (byte) 0xEE, (byte) 0xCA, (byte) 0xF2, + (byte) 0x33, (byte) 0x7D, (byte) 0xF2, (byte) 0x41, (byte) 0x52, (byte) 0x0B, (byte) 0x9B, (byte) 0x1B, + (byte) 0x2D, (byte) 0x89, (byte) 0x38, (byte) 0xEC, (byte) 0x24, (byte) 0x60, (byte) 0x40, (byte) 0x40, + (byte) 0x6F, (byte) 0xB6, (byte) 0x6F, (byte) 0x86, (byte) 0xB5, (byte) 0x0A, (byte) 0x3D, (byte) 0x98, + (byte) 0x77, (byte) 0x3F, (byte) 0x59, (byte) 0x41, (byte) 0x3E, (byte) 0x4D, (byte) 0xE4, (byte) 0x4E, + (byte) 0x91, (byte) 0xCD, (byte) 0x8E, (byte) 0x33, (byte) 0x60, (byte) 0x16, (byte) 0x8D, (byte) 0xAB, + (byte) 0x04, (byte) 0x14, (byte) 0xE8, (byte) 0x76, (byte) 0xF1, (byte) 0x06, (byte) 0xCD, (byte) 0x4A, + (byte) 0x88, (byte) 0xC7, (byte) 0x69, (byte) 0x6B, (byte) 0xC6, (byte) 0xDA, (byte) 0x9E, (byte) 0x09 + }; + private static final byte[] SHA256withRSA_Vector2Signature = new byte[] { (byte) 0x18, (byte) 0x6e, (byte) 0x31, (byte) 0x1f, (byte) 0x1d, (byte) 0x44, (byte) 0x09, (byte) 0x3e, (byte) 0xa0, (byte) 0xc4, (byte) 0x3d, (byte) 0xb4, (byte) 0x1b, (byte) 0xf2, (byte) 0xd8, (byte) 0xa4, @@ -871,6 +1100,30 @@ public class SignatureTest extends TestCase { assertTrue("Signature must verify correctly", sig.verify(signature)); } + public void testSign_SHA224withRSA_Key_Success() throws Exception { + KeyFactory kf = KeyFactory.getInstance("RSA"); + RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(RSA_2048_modulus, + RSA_2048_privateExponent); + + final PrivateKey privKey = kf.generatePrivate(keySpec); + + Signature sig = Signature.getInstance("SHA224withRSA"); + sig.initSign(privKey); + sig.update(Vector2Data); + + byte[] signature = sig.sign(); + assertNotNull("Signature must not be null", signature); + assertTrue("Signature should match expected", + Arrays.equals(signature, SHA224withRSA_Vector2Signature)); + + RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(RSA_2048_modulus, + RSA_2048_publicExponent); + PublicKey pubKey = kf.generatePublic(pubKeySpec); + sig.initVerify(pubKey); + sig.update(Vector2Data); + assertTrue("Signature must verify correctly", sig.verify(signature)); + } + public void testSign_SHA256withRSA_Key_Success() throws Exception { KeyFactory kf = KeyFactory.getInstance("RSA"); RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(RSA_2048_modulus, @@ -1225,6 +1478,34 @@ public class SignatureTest extends TestCase { (byte) 0xdc, (byte) 0x73, (byte) 0x3d, (byte) 0xf3, (byte) 0x51, (byte) 0xc0, (byte) 0x57, }; + /** + * A possible signature using SHA224withDSA of Vector2Data. Note that DSS is + * randomized, so this won't be the exact signature you'll get out of + * another signing operation unless you use a fixed RNG. + */ + public static final byte[] SHA224withDSA_Vector2Signature = new byte[] { + (byte) 0x30, (byte) 0x2D, (byte) 0x02, (byte) 0x15, (byte) 0x00, (byte) 0xAD, (byte) 0xE5, (byte) 0x6D, + (byte) 0xF5, (byte) 0x11, (byte) 0x8D, (byte) 0x2E, (byte) 0x62, (byte) 0x5D, (byte) 0x98, (byte) 0x8A, + (byte) 0xC4, (byte) 0x88, (byte) 0x7E, (byte) 0xE6, (byte) 0xA3, (byte) 0x44, (byte) 0x99, (byte) 0xEF, + (byte) 0x49, (byte) 0x02, (byte) 0x14, (byte) 0x15, (byte) 0x3E, (byte) 0x32, (byte) 0xD6, (byte) 0xF9, + (byte) 0x79, (byte) 0x2C, (byte) 0x60, (byte) 0x6E, (byte) 0xF9, (byte) 0xA9, (byte) 0x78, (byte) 0xE7, + (byte) 0x4B, (byte) 0x87, (byte) 0x08, (byte) 0x96, (byte) 0x60, (byte) 0xDE, (byte) 0xB5 + }; + + /** + * A possible signature using SHA256withDSA of Vector2Data. Note that DSS is + * randomized, so this won't be the exact signature you'll get out of + * another signing operation unless you use a fixed RNG. + */ + public static final byte[] SHA256withDSA_Vector2Signature = new byte[] { + (byte) 0x30, (byte) 0x2D, (byte) 0x02, (byte) 0x14, (byte) 0x0A, (byte) 0xB1, (byte) 0x74, (byte) 0x45, + (byte) 0xE1, (byte) 0x63, (byte) 0x43, (byte) 0x68, (byte) 0x65, (byte) 0xBC, (byte) 0xCA, (byte) 0x45, + (byte) 0x27, (byte) 0x11, (byte) 0x4D, (byte) 0x52, (byte) 0xFB, (byte) 0x22, (byte) 0x93, (byte) 0xDD, + (byte) 0x02, (byte) 0x15, (byte) 0x00, (byte) 0x98, (byte) 0x32, (byte) 0x1A, (byte) 0x16, (byte) 0x77, + (byte) 0x49, (byte) 0xA7, (byte) 0x78, (byte) 0xFD, (byte) 0xE0, (byte) 0xF7, (byte) 0x71, (byte) 0xD4, + (byte) 0x80, (byte) 0x50, (byte) 0xA7, (byte) 0xDD, (byte) 0x94, (byte) 0xD1, (byte) 0x6C + }; + public void testSign_SHA1withDSA_Key_Success() throws Exception { KeyFactory kf = KeyFactory.getInstance("DSA"); DSAPrivateKeySpec keySpec = new DSAPrivateKeySpec(DSA_priv, DSA_P, DSA_Q, DSA_G); @@ -1255,10 +1536,73 @@ public class SignatureTest extends TestCase { assertTrue("Signature must verify correctly", sig.verify(SHA1withDSA_Vector2Signature)); } + public void testSign_SHA224withDSA_Key_Success() throws Exception { + KeyFactory kf = KeyFactory.getInstance("DSA"); + DSAPrivateKeySpec keySpec = new DSAPrivateKeySpec(DSA_priv, DSA_P, DSA_Q, DSA_G); + PrivateKey privKey = kf.generatePrivate(keySpec); + + Signature sig = Signature.getInstance("SHA224withDSA"); + sig.initSign(privKey); + sig.update(Vector2Data); + + byte[] signature = sig.sign(); + assertNotNull("Signature must not be null", signature); + + DSAPublicKeySpec pubKeySpec = new DSAPublicKeySpec(DSA_pub, DSA_P, DSA_Q, DSA_G); + PublicKey pubKey = kf.generatePublic(pubKeySpec); + sig.initVerify(pubKey); + sig.update(Vector2Data); + assertTrue("Signature must verify correctly", sig.verify(signature)); + } + + public void testVerify_SHA224withDSA_Key_Success() throws Exception { + KeyFactory kf = KeyFactory.getInstance("DSA"); + DSAPublicKeySpec pubKeySpec = new DSAPublicKeySpec(DSA_pub, DSA_P, DSA_Q, DSA_G); + PublicKey pubKey = kf.generatePublic(pubKeySpec); + + Signature sig = Signature.getInstance("SHA224withDSA"); + sig.initVerify(pubKey); + sig.update(Vector2Data); + assertTrue("Signature must verify correctly", sig.verify(SHA224withDSA_Vector2Signature)); + } + + public void testSign_SHA256withDSA_Key_Success() throws Exception { + KeyFactory kf = KeyFactory.getInstance("DSA"); + DSAPrivateKeySpec keySpec = new DSAPrivateKeySpec(DSA_priv, DSA_P, DSA_Q, DSA_G); + PrivateKey privKey = kf.generatePrivate(keySpec); + + Signature sig = Signature.getInstance("SHA256withDSA"); + sig.initSign(privKey); + sig.update(Vector2Data); + + byte[] signature = sig.sign(); + assertNotNull("Signature must not be null", signature); + + DSAPublicKeySpec pubKeySpec = new DSAPublicKeySpec(DSA_pub, DSA_P, DSA_Q, DSA_G); + PublicKey pubKey = kf.generatePublic(pubKeySpec); + sig.initVerify(pubKey); + sig.update(Vector2Data); + assertTrue("Signature must verify correctly", sig.verify(signature)); + } + + public void testVerify_SHA256withDSA_Key_Success() throws Exception { + KeyFactory kf = KeyFactory.getInstance("DSA"); + DSAPublicKeySpec pubKeySpec = new DSAPublicKeySpec(DSA_pub, DSA_P, DSA_Q, DSA_G); + PublicKey pubKey = kf.generatePublic(pubKeySpec); + + Signature sig = Signature.getInstance("SHA256withDSA"); + sig.initVerify(pubKey); + sig.update(Vector2Data); + assertTrue("Signature must verify correctly", sig.verify(SHA256withDSA_Vector2Signature)); + } + // NetscapeCertRequest looks up Signature algorithms by OID from // BC but BC version 1.47 had registration bugs and MD5withRSA was // overlooked. http://b/7453821 public void testGetInstanceFromOID() throws Exception { + if (StandardNames.IS_RI) { + return; + } assertBouncyCastleSignatureFromOID("1.2.840.113549.1.1.4"); // MD5withRSA assertBouncyCastleSignatureFromOID("1.2.840.113549.1.1.5"); // SHA1withRSA assertBouncyCastleSignatureFromOID("1.3.14.3.2.29"); // SHA1withRSA @@ -1273,4 +1617,33 @@ public class SignatureTest extends TestCase { assertNotNull(oid, signature); assertEquals(oid, signature.getAlgorithm()); } + + private final int THREAD_COUNT = 10; + + private void testSignature_MultipleThreads_Misuse(final Signature s) throws Exception { + ExecutorService es = Executors.newFixedThreadPool(THREAD_COUNT); + + final CountDownLatch latch = new CountDownLatch(THREAD_COUNT); + final byte[] message = new byte[64]; + + for (int i = 0; i < THREAD_COUNT; i++) { + es.submit(new Callable<Void>() { + @Override + public Void call() throws Exception { + // Try to make sure all the threads are ready first. + latch.countDown(); + latch.await(); + + for (int j = 0; j < 100; j++) { + s.update(message); + s.sign(); + } + + return null; + } + }); + } + es.shutdown(); + assertTrue("Test should not timeout", es.awaitTermination(1, TimeUnit.MINUTES)); + } } diff --git a/luni/src/test/java/libcore/java/security/cert/CRLReasonTest.java b/luni/src/test/java/libcore/java/security/cert/CRLReasonTest.java new file mode 100644 index 0000000..8030de1 --- /dev/null +++ b/luni/src/test/java/libcore/java/security/cert/CRLReasonTest.java @@ -0,0 +1,67 @@ +/* + * Copyright 2014 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.security.cert; + +import java.security.cert.CRLReason; + +import junit.framework.TestCase; + +public class CRLReasonTest extends TestCase { + public void testCryptoPrimitive_ordinal_ExpectedValues() throws Exception { + assertEquals("UNSPECIFIED", 0, CRLReason.UNSPECIFIED.ordinal()); + assertEquals("KEY_COMPROMISE", 1, CRLReason.KEY_COMPROMISE.ordinal()); + assertEquals("CA_COMPROMISE", 2, CRLReason.CA_COMPROMISE.ordinal()); + assertEquals("AFFILIATION_CHANGED", 3, CRLReason.AFFILIATION_CHANGED.ordinal()); + assertEquals("SUPERSEDED", 4, CRLReason.SUPERSEDED.ordinal()); + assertEquals("CESSATION_OF_OPERATION", 5, CRLReason.CESSATION_OF_OPERATION.ordinal()); + assertEquals("CERTIFICATE_HOLD", 6, CRLReason.CERTIFICATE_HOLD.ordinal()); + assertEquals("UNUSED", 7, CRLReason.UNUSED.ordinal()); + assertEquals("REMOVE_FROM_CRL", 8, CRLReason.REMOVE_FROM_CRL.ordinal()); + assertEquals("PRIVILEGE_WITHDRAWN", 9, CRLReason.PRIVILEGE_WITHDRAWN.ordinal()); + assertEquals("AA_COMPROMISE", 10, CRLReason.AA_COMPROMISE.ordinal()); + } + + public void testCRLReason_values_ExpectedValues() throws Exception { + CRLReason[] reasons = CRLReason.values(); + assertEquals(11, reasons.length); + assertEquals(CRLReason.UNSPECIFIED, reasons[0]); + assertEquals(CRLReason.KEY_COMPROMISE, reasons[1]); + assertEquals(CRLReason.CA_COMPROMISE, reasons[2]); + assertEquals(CRLReason.AFFILIATION_CHANGED, reasons[3]); + assertEquals(CRLReason.SUPERSEDED, reasons[4]); + assertEquals(CRLReason.CESSATION_OF_OPERATION, reasons[5]); + assertEquals(CRLReason.CERTIFICATE_HOLD, reasons[6]); + assertEquals(CRLReason.UNUSED, reasons[7]); + assertEquals(CRLReason.REMOVE_FROM_CRL, reasons[8]); + assertEquals(CRLReason.PRIVILEGE_WITHDRAWN, reasons[9]); + assertEquals(CRLReason.AA_COMPROMISE, reasons[10]); + } + + public void testCRLReason_valueOf_ExpectedValues() throws Exception { + assertEquals(CRLReason.UNSPECIFIED, CRLReason.valueOf("UNSPECIFIED")); + assertEquals(CRLReason.KEY_COMPROMISE, CRLReason.valueOf("KEY_COMPROMISE")); + assertEquals(CRLReason.CA_COMPROMISE, CRLReason.valueOf("CA_COMPROMISE")); + assertEquals(CRLReason.AFFILIATION_CHANGED, CRLReason.valueOf("AFFILIATION_CHANGED")); + assertEquals(CRLReason.SUPERSEDED, CRLReason.valueOf("SUPERSEDED")); + assertEquals(CRLReason.CESSATION_OF_OPERATION, CRLReason.valueOf("CESSATION_OF_OPERATION")); + assertEquals(CRLReason.CERTIFICATE_HOLD, CRLReason.valueOf("CERTIFICATE_HOLD")); + assertEquals(CRLReason.UNUSED, CRLReason.valueOf("UNUSED")); + assertEquals(CRLReason.REMOVE_FROM_CRL, CRLReason.valueOf("REMOVE_FROM_CRL")); + assertEquals(CRLReason.PRIVILEGE_WITHDRAWN, CRLReason.valueOf("PRIVILEGE_WITHDRAWN")); + assertEquals(CRLReason.AA_COMPROMISE, CRLReason.valueOf("AA_COMPROMISE")); + } +} diff --git a/luni/src/test/java/libcore/java/security/cert/OldPKIXParametersTest.java b/luni/src/test/java/libcore/java/security/cert/OldPKIXParametersTest.java index d69e0e2..0832dae 100644 --- a/luni/src/test/java/libcore/java/security/cert/OldPKIXParametersTest.java +++ b/luni/src/test/java/libcore/java/security/cert/OldPKIXParametersTest.java @@ -22,7 +22,6 @@ package libcore.java.security.cert; -import dalvik.annotation.BrokenTest; import java.io.ByteArrayInputStream; import java.security.InvalidAlgorithmParameterException; import java.security.KeyStore; @@ -176,7 +175,7 @@ public class OldPKIXParametersTest extends TestCase { * @throws InvalidAlgorithmParameterException * @throws KeyStoreException */ - @BrokenTest("Fails in CTS environment, but passes in CoreTestRunner") + // Broken Test: Fails in CTS environment, but passes in CoreTestRunner public final void testPKIXParametersKeyStore04() throws Exception { diff --git a/luni/src/test/java/libcore/java/security/cert/X509CRLTest.java b/luni/src/test/java/libcore/java/security/cert/X509CRLTest.java index fa920ce..42de50a 100644 --- a/luni/src/test/java/libcore/java/security/cert/X509CRLTest.java +++ b/luni/src/test/java/libcore/java/security/cert/X509CRLTest.java @@ -30,12 +30,14 @@ import java.security.Provider; import java.security.Security; import java.security.SignatureException; import java.security.cert.CRL; +import java.security.cert.CRLReason; import java.security.cert.CertificateFactory; import java.security.cert.X509CRL; import java.security.cert.X509CRLEntry; import java.security.cert.X509Certificate; import java.text.SimpleDateFormat; import java.util.Arrays; +import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Locale; @@ -120,7 +122,7 @@ public class X509CRLTest extends TestCase { private Map<String, Date> getCrlDates(String name) throws Exception { Map<String, Date> dates = new HashMap<String, Date>(); - final SimpleDateFormat sdf = new SimpleDateFormat("MMM dd HH:mm:ss yyyy zzz"); + final SimpleDateFormat sdf = new SimpleDateFormat("MMM dd HH:mm:ss yyyy zzz", Locale.US); final InputStream ris = Support_Resources.getStream(name); try { @@ -316,6 +318,22 @@ public class X509CRLTest extends TestCase { assertEquals(result1, result2); } + /* + * This is needed because the certificate revocation in our CRL can be a + * couple seconds ahead of the lastUpdate time in the CRL. + */ + private static void assertDateSlightlyBefore(Date expected, Date actual) throws Exception { + Calendar c = Calendar.getInstance(); + + // Make sure it's within 2 seconds of expected. + c.setTime(expected); + c.add(Calendar.SECOND, -2); + assertTrue(actual.after(c.getTime())); + + // Before or equal... + assertTrue(actual.before(expected) || actual.equals(expected)); + } + private void assertRsaCrlEntry(CertificateFactory f, X509CRLEntry rsaEntry) throws Exception { assertNotNull(rsaEntry); @@ -324,7 +342,8 @@ public class X509CRLTest extends TestCase { Date expectedDate = dates.get("lastUpdate"); assertEquals(rsaCert.getSerialNumber(), rsaEntry.getSerialNumber()); - assertDateEquals(expectedDate, rsaEntry.getRevocationDate()); + assertDateSlightlyBefore(expectedDate, rsaEntry.getRevocationDate()); + assertNull(rsaEntry.getRevocationReason()); assertNull(rsaEntry.getCertificateIssuer()); assertFalse(rsaEntry.hasExtensions()); assertNull(rsaEntry.getCriticalExtensionOIDs()); @@ -334,18 +353,24 @@ public class X509CRLTest extends TestCase { } private void assertDsaCrlEntry(CertificateFactory f, X509CRLEntry dsaEntry) throws Exception { + assertNotNull(dsaEntry); + X509Certificate dsaCert = getCertificate(f, CERT_DSA); Map<String, Date> dates = getCrlDates(CRL_RSA_DSA_DATES); Date expectedDate = dates.get("lastUpdate"); assertEquals(dsaCert.getSerialNumber(), dsaEntry.getSerialNumber()); - assertDateEquals(expectedDate, dsaEntry.getRevocationDate()); + assertDateSlightlyBefore(expectedDate, dsaEntry.getRevocationDate()); + assertEquals(CRLReason.CESSATION_OF_OPERATION, dsaEntry.getRevocationReason()); assertNull(dsaEntry.getCertificateIssuer()); assertTrue(dsaEntry.hasExtensions()); - /* TODO: get the OID */ assertNotNull(dsaEntry.getCriticalExtensionOIDs()); - /* TODO: get the OID */ + assertEquals(0, dsaEntry.getCriticalExtensionOIDs().size()); assertNotNull(dsaEntry.getNonCriticalExtensionOIDs()); + assertEquals(1, dsaEntry.getNonCriticalExtensionOIDs().size()); + assertTrue(Arrays.toString(dsaEntry.getNonCriticalExtensionOIDs().toArray()), + dsaEntry.getNonCriticalExtensionOIDs().contains("2.5.29.21")); + System.out.println(Arrays.toString(dsaEntry.getExtensionValue("2.5.29.21"))); assertNotNull(dsaEntry.toString()); } @@ -362,13 +387,16 @@ public class X509CRLTest extends TestCase { assertEquals(1, entries.size()); for (X509CRLEntry e : entries) { assertRsaCrlEntry(f, e); + assertRsaCrlEntry(f, crlRsa.getRevokedCertificate(e.getSerialNumber())); } X509CRL crlRsaDsa = getCRL(f, CRL_RSA_DSA); Set<? extends X509CRLEntry> entries2 = crlRsaDsa.getRevokedCertificates(); assertEquals(2, entries2.size()); assertRsaCrlEntry(f, crlRsaDsa.getRevokedCertificate(rsaCert)); + assertRsaCrlEntry(f, crlRsaDsa.getRevokedCertificate(rsaCert.getSerialNumber())); assertDsaCrlEntry(f, crlRsaDsa.getRevokedCertificate(dsaCert)); + assertDsaCrlEntry(f, crlRsaDsa.getRevokedCertificate(dsaCert.getSerialNumber())); } private void getSigAlgParams(CertificateFactory f) throws Exception { diff --git a/luni/src/test/java/libcore/java/security/cert/X509CertificateTest.java b/luni/src/test/java/libcore/java/security/cert/X509CertificateTest.java index ffddcbe..c35f8e6 100644 --- a/luni/src/test/java/libcore/java/security/cert/X509CertificateTest.java +++ b/luni/src/test/java/libcore/java/security/cert/X509CertificateTest.java @@ -170,7 +170,8 @@ public class X509CertificateTest extends TestCase { final InputStream ris = Support_Resources.getStream("x509/cert-rsa-dates.txt"); try { // notBefore=Dec 26 00:19:14 2012 GMT - final SimpleDateFormat sdf = new SimpleDateFormat("MMM dd HH:mm:ss yyyy zzz"); + final SimpleDateFormat sdf = + new SimpleDateFormat("MMM dd HH:mm:ss yyyy zzz", Locale.US); final BufferedReader buf = new BufferedReader(new InputStreamReader(ris)); String line = buf.readLine(); diff --git a/luni/src/test/java/libcore/java/sql/ConnectionTest.java b/luni/src/test/java/libcore/java/sql/ConnectionTest.java new file mode 100644 index 0000000..02046fc --- /dev/null +++ b/luni/src/test/java/libcore/java/sql/ConnectionTest.java @@ -0,0 +1,69 @@ +package libcore.java.sql; + +import junit.framework.TestCase; + +import java.io.File; +import java.io.IOException; +import java.sql.Connection; +import java.sql.Driver; +import java.sql.DriverManager; + +public class ConnectionTest extends TestCase { + + private File dbFile = null; + private String connectionURL = null; + + @Override + public void setUp() throws Exception { + super.setUp(); + + // Trigger the static initializer that will cause the driver to register itself with + // DriverManager. + Class.forName("SQLite.JDBCDriver"); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + if (dbFile != null) { + dbFile.delete(); + } + } + + public void testDriverManager_getConnection() throws Exception { + Connection c = DriverManager.getConnection(getConnectionURL()); + assertFalse(c.isClosed()); + c.close(); + assertTrue(c.isClosed()); + } + + public void testConnect() throws Exception { + Driver driver = DriverManager.getDriver(getConnectionURL()); + assertNotNull(driver); + Connection c = driver.connect(getConnectionURL(), null); + assertFalse(c.isClosed()); + c.close(); + assertTrue(c.isClosed()); + } + + private String getConnectionURL() { + if (connectionURL == null) { + String tmp = System.getProperty("java.io.tmpdir"); + File tmpDir = new File(tmp); + if (tmpDir.isDirectory()) { + try { + dbFile = File.createTempFile("OldJDBCDriverTest", ".db", tmpDir); + } catch (IOException e) { + System.err.println("error creating temporary DB file."); + } + dbFile.deleteOnExit(); + } else { + System.err.println("java.io.tmpdir does not exist"); + } + + connectionURL = "jdbc:sqlite:/" + dbFile.getPath(); + } + + return connectionURL; + } +} diff --git a/luni/src/test/java/libcore/java/sql/DriverTest.java b/luni/src/test/java/libcore/java/sql/DriverTest.java new file mode 100644 index 0000000..59d13bd --- /dev/null +++ b/luni/src/test/java/libcore/java/sql/DriverTest.java @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2008 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.sql; + +import junit.framework.TestCase; + +import SQLite.JDBCDriver; + +import java.sql.Driver; +import java.sql.DriverManager; +import java.sql.DriverPropertyInfo; +import java.sql.SQLException; + +public final class DriverTest extends TestCase { + + public static final String SQLITE_JDBC_URL = "jdbc:sqlite:/only_used_at_connect_time"; + + @Override + public void setUp() throws Exception { + super.setUp(); + + // Trigger the static initializer that will cause the driver to register itself with + // DriverManager. + Class.forName("SQLite.JDBCDriver"); + } + + public void testDriverImplementation() throws Exception { + Driver driver = getDriver(); + assertTrue(driver instanceof JDBCDriver); + } + + public void testAcceptsURL() throws Exception { + Driver driver = getDriver(); + assertTrue(driver.acceptsURL(SQLITE_JDBC_URL)); + } + + public void testGetMajorVersion() throws Exception { + assertTrue(getDriver().getMajorVersion() > 0); + } + + public void testGetMinorVersion() throws Exception { + assertTrue(getDriver().getMinorVersion() > 0); + } + + public void testGetPropertyInfo() throws Exception { + Driver driver = getDriver(); + DriverPropertyInfo[] info = driver.getPropertyInfo(SQLITE_JDBC_URL, null); + assertNotNull(info); + assertTrue(info.length > 0); + } + + public void testJdbcCompliant() throws Exception { + // The SQLite JDBC driver used by these tests is not actually JDBC compliant. + assertFalse(getDriver().jdbcCompliant()); + } + + private Driver getDriver() throws SQLException { + Driver driver = DriverManager.getDriver(SQLITE_JDBC_URL); + assertNotNull(driver); + return driver; + } +} diff --git a/luni/src/test/java/libcore/java/sql/OldResultSetTest.java b/luni/src/test/java/libcore/java/sql/OldResultSetTest.java index ea18db6..a1654cf 100644 --- a/luni/src/test/java/libcore/java/sql/OldResultSetTest.java +++ b/luni/src/test/java/libcore/java/sql/OldResultSetTest.java @@ -80,7 +80,7 @@ public final class OldResultSetTest extends OldSQLTest { try { target.close(); - target.beforeFirst(); + target.afterLast(); fail("Should get SQLException"); } catch (SQLException e) { } diff --git a/luni/src/test/java/libcore/java/sql/OldTimestampTest.java b/luni/src/test/java/libcore/java/sql/OldTimestampTest.java deleted file mode 100644 index ab2034b..0000000 --- a/luni/src/test/java/libcore/java/sql/OldTimestampTest.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.sql; - -import java.sql.Timestamp; -import java.util.TimeZone; -import junit.framework.TestCase; - -public final class OldTimestampTest extends TestCase { - - public void test_toString() { - TimeZone.setDefault(TimeZone.getTimeZone("UTC")); - - Timestamp t1 = new Timestamp(Long.MIN_VALUE); - assertEquals("292278994-08-17 07:12:55.192", t1.toString()); - - Timestamp t2 = new Timestamp(Long.MIN_VALUE + 1); - assertEquals("292278994-08-17 07:12:55.193", t2.toString()); - - Timestamp t3 = new Timestamp(Long.MIN_VALUE + 807); - assertEquals("292278994-08-17 07:12:55.999", t3.toString()); - - Timestamp t4 = new Timestamp(Long.MIN_VALUE + 808); - assertEquals("292269055-12-02 16:47:05.0", t4.toString()); - } -} diff --git a/luni/src/test/java/libcore/java/sql/TimestampTest.java b/luni/src/test/java/libcore/java/sql/TimestampTest.java new file mode 100644 index 0000000..2985848 --- /dev/null +++ b/luni/src/test/java/libcore/java/sql/TimestampTest.java @@ -0,0 +1,147 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.sql; + +import java.sql.Timestamp; +import java.util.TimeZone; +import junit.framework.TestCase; + +public final class TimestampTest extends TestCase { + + public void testToString() { + // Timestamp uses the current default timezone in toString() to convert to + // human-readable strings. + TimeZone defaultTimeZone = TimeZone.getDefault(); + TimeZone.setDefault(TimeZone.getTimeZone("UTC")); + try { + Timestamp t1 = new Timestamp(Long.MIN_VALUE); + assertEquals("292278994-08-17 07:12:55.192", t1.toString()); + + Timestamp t2 = new Timestamp(Long.MIN_VALUE + 1); + assertEquals("292278994-08-17 07:12:55.193", t2.toString()); + + Timestamp t3 = new Timestamp(Long.MIN_VALUE + 807); + assertEquals("292278994-08-17 07:12:55.999", t3.toString()); + + Timestamp t4 = new Timestamp(Long.MIN_VALUE + 808); + assertEquals("292269055-12-02 16:47:05.0", t4.toString()); + } finally { + TimeZone.setDefault(defaultTimeZone); + } + } + + public void testValueOf() { + // Timestamp uses the current default timezone in valueOf(String) to convert + // from human-readable strings. + TimeZone defaultTimeZone = TimeZone.getDefault(); + TimeZone.setDefault(TimeZone.getTimeZone("GMT")); + try { + Timestamp t1 = Timestamp.valueOf("2001-12-31 21:45:57.123456789"); + assertEquals(1009835157000L + 123456789 / 1000000, t1.getTime()); + assertEquals(123456789, t1.getNanos()); + + Timestamp t2 = Timestamp.valueOf("2001-01-02 01:05:07.123"); + assertEquals(978397507000L + 123000000 / 1000000, t2.getTime()); + assertEquals(123000000, t2.getNanos()); + + Timestamp t3 = Timestamp.valueOf("2001-01-02 01:05:07"); + assertEquals(978397507000L, t3.getTime()); + assertEquals(0, t3.getNanos()); + } finally { + TimeZone.setDefault(defaultTimeZone); + } + } + + public void testValueOfInvalid() { + try { + Timestamp.valueOf(""); + fail(); + } catch (IllegalArgumentException expected) { } + + try { + Timestamp.valueOf("+2001-12-31"); + fail(); + } catch (IllegalArgumentException expected) { } + + try { + Timestamp.valueOf("2001-+12-31"); + fail(); + } catch (IllegalArgumentException expected) { } + + try { + Timestamp.valueOf("2001-12-+31"); + fail(); + } catch (IllegalArgumentException expected) { } + + try { + Timestamp.valueOf("-2001-12-31"); + fail(); + } catch (IllegalArgumentException expected) { } + + try { + Timestamp.valueOf("2001--12-31"); + fail(); + } catch (IllegalArgumentException expected) { } + + try { + Timestamp.valueOf("2001-12--31"); + fail(); + } catch (IllegalArgumentException expected) { } + + try { + Timestamp.valueOf("2001--"); + fail(); + } catch (IllegalArgumentException expected) { } + + try { + Timestamp.valueOf("2001--31"); + fail(); + } catch (IllegalArgumentException expected) { } + + try { + Timestamp.valueOf("-12-31"); + fail(); + } catch (IllegalArgumentException expected) { } + + try { + Timestamp.valueOf("-12-"); + fail(); + } catch (IllegalArgumentException expected) { } + + try { + Timestamp.valueOf("--31"); + fail(); + } catch (IllegalArgumentException expected) { } + + try { + Timestamp.valueOf("2001-12-31 21:45:57.+12345678"); + fail(); + } catch (IllegalArgumentException expected) { } + + try { + Timestamp.valueOf("2001-12-31 21:45:57.-12345678"); + fail(); + } catch (IllegalArgumentException expected) { } + + try { + Timestamp.valueOf("2001-12-31 21:45:57.1234567891"); + fail(); + } catch (IllegalArgumentException expected) { } + } + +} diff --git a/luni/src/test/java/libcore/java/text/CollatorTest.java b/luni/src/test/java/libcore/java/text/CollatorTest.java index 0a61f04..0f65b20 100644 --- a/luni/src/test/java/libcore/java/text/CollatorTest.java +++ b/luni/src/test/java/libcore/java/text/CollatorTest.java @@ -88,7 +88,7 @@ public class CollatorTest extends junit.framework.TestCase { } public void testEqualsObject() throws ParseException { - String rule = "< a < b < c < d < e"; + String rule = "&9 < a < b < c < d < e"; RuleBasedCollator coll = new RuleBasedCollator(rule); assertEquals(Collator.TERTIARY, coll.getStrength()); @@ -109,7 +109,7 @@ public class CollatorTest extends junit.framework.TestCase { // Regression test for HARMONY-1352, that doesn't get run in the harmony test suite because // of an earlier failure. try { - new RuleBasedCollator("< a< b< c< d").getCollationElementIterator((CharacterIterator) null); + new RuleBasedCollator("&9 < a< b< c< d").getCollationElementIterator((CharacterIterator) null); fail("NullPointerException expected"); } catch (NullPointerException expected) { } @@ -139,7 +139,7 @@ public class CollatorTest extends junit.framework.TestCase { } public void testGetCollationElementIteratorString_de_DE() throws Exception { - assertGetCollationElementIteratorString(new Locale("de", "DE", ""), "\u00e6b", 0, 1, 1, 1, 1, 2); + assertGetCollationElementIteratorString(new Locale("de", "DE", ""), "\u00e6b", 0, 1, 1, 2); } public void testGetCollationElementIteratorCharacterIterator_es() throws Exception { @@ -147,6 +147,6 @@ public class CollatorTest extends junit.framework.TestCase { } public void testGetCollationElementIteratorCharacterIterator_de_DE() throws Exception { - assertGetCollationElementIteratorCharacterIterator(new Locale("de", "DE", ""), "\u00e6b", 0, 1, 1, 1, 1, 2); + assertGetCollationElementIteratorCharacterIterator(new Locale("de", "DE", ""), "\u00e6b", 0, 1, 1, 2); } } diff --git a/luni/src/test/java/libcore/java/text/DateFormatSymbolsTest.java b/luni/src/test/java/libcore/java/text/DateFormatSymbolsTest.java index e13e4df..057cd17 100644 --- a/luni/src/test/java/libcore/java/text/DateFormatSymbolsTest.java +++ b/luni/src/test/java/libcore/java/text/DateFormatSymbolsTest.java @@ -46,6 +46,10 @@ public class DateFormatSymbolsTest extends junit.framework.TestCase { } public void testSerialization() throws Exception { + // Set the default locale. The default locale used to determine what strings were used by + // the DateFormatSymbols after deserialization. See http://b/16502916 + Locale.setDefault(Locale.US); + // The Polish language needs stand-alone month and weekday names. Locale pl = new Locale("pl"); DateFormatSymbols originalDfs = new DateFormatSymbols(pl); @@ -60,17 +64,16 @@ public class DateFormatSymbolsTest extends junit.framework.TestCase { DateFormatSymbols deserializedDfs = (DateFormatSymbols) in.readObject(); assertEquals(-1, in.read()); - // The two objects should claim to be equal, even though they aren't really. + // The two objects be equal. assertEquals(originalDfs, deserializedDfs); // The original differentiates between regular month names and stand-alone month names... assertEquals("stycznia", formatDate(pl, "MMMM", originalDfs)); assertEquals("stycze\u0144", formatDate(pl, "LLLL", originalDfs)); - // But the deserialized object is screwed because the RI's serialized form doesn't - // contain the locale or the necessary strings. Don't serialize DateFormatSymbols, folks! + // And so does the deserialized version. assertEquals("stycznia", formatDate(pl, "MMMM", deserializedDfs)); - assertEquals("January", formatDate(pl, "LLLL", deserializedDfs)); + assertEquals("stycze\u0144", formatDate(pl, "LLLL", deserializedDfs)); } private String formatDate(Locale l, String fmt, DateFormatSymbols dfs) { diff --git a/luni/src/test/java/libcore/java/text/DecimalFormatSymbolsTest.java b/luni/src/test/java/libcore/java/text/DecimalFormatSymbolsTest.java index 8b24c6d..619c38e 100644 --- a/luni/src/test/java/libcore/java/text/DecimalFormatSymbolsTest.java +++ b/luni/src/test/java/libcore/java/text/DecimalFormatSymbolsTest.java @@ -24,18 +24,21 @@ import java.text.DecimalFormatSymbols; import java.util.Locale; public class DecimalFormatSymbolsTest extends junit.framework.TestCase { - private void checkLocaleIsEquivalentToRoot(Locale locale) { - DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(locale); - assertEquals(DecimalFormatSymbols.getInstance(Locale.ROOT), dfs); - } public void test_getInstance_unknown_or_invalid_locale() throws Exception { - // TODO: we fail these tests because ROOT has "INF" for infinity but 'dfs' has "\u221e". - // On the RI, ROOT has "\u221e" too, but DecimalFormatSymbols.equals appears to be broken; - // it returns false for objects that -- if you compare their externally visible state -- - // are equal. It could be that they're accidentally checking the Locale. + // http://b/17374604: this test passes on the host but fails on the target. + // ICU uses setlocale(3) to determine its default locale, and glibc (on my box at least) + // returns "en_US.UTF-8". bionic before L returned NULL and in L returns "C.UTF-8", both + // of which get treated as "en_US_POSIX". What that means for this test is that you get + // "INF" for infinity instead of "\u221e". + // On the RI, this test fails for a different reason: their DecimalFormatSymbols.equals + // appears to be broken. It could be that they're accidentally checking the Locale field? checkLocaleIsEquivalentToRoot(new Locale("xx", "XX")); checkLocaleIsEquivalentToRoot(new Locale("not exist language", "not exist country")); } + private void checkLocaleIsEquivalentToRoot(Locale locale) { + DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(locale); + assertEquals(DecimalFormatSymbols.getInstance(Locale.ROOT), dfs); + } // http://code.google.com/p/android/issues/detail?id=14495 public void testSerialization() throws Exception { diff --git a/luni/src/test/java/libcore/java/text/DecimalFormatTest.java b/luni/src/test/java/libcore/java/text/DecimalFormatTest.java index 1e40f8a..0eae20a 100644 --- a/luni/src/test/java/libcore/java/text/DecimalFormatTest.java +++ b/luni/src/test/java/libcore/java/text/DecimalFormatTest.java @@ -21,7 +21,9 @@ import java.math.BigInteger; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; +import java.text.FieldPosition; import java.text.NumberFormat; +import java.text.ParsePosition; import java.util.Currency; import java.util.Locale; @@ -122,21 +124,21 @@ public class DecimalFormatTest extends junit.framework.TestCase { df.setMaximumFractionDigits(2); df.setMultiplier(2); assertEquals(df.format(BigDecimal.valueOf(0.16)), - df.format(BigDecimal.valueOf(0.16).doubleValue())); + df.format(BigDecimal.valueOf(0.16).doubleValue())); assertEquals(df.format(BigDecimal.valueOf(0.0293)), - df.format(BigDecimal.valueOf(0.0293).doubleValue())); + df.format(BigDecimal.valueOf(0.0293).doubleValue())); assertEquals(df.format(BigDecimal.valueOf(0.006)), - df.format(BigDecimal.valueOf(0.006).doubleValue())); + df.format(BigDecimal.valueOf(0.006).doubleValue())); assertEquals(df.format(BigDecimal.valueOf(0.00283)), - df.format(BigDecimal.valueOf(0.00283).doubleValue())); + df.format(BigDecimal.valueOf(0.00283).doubleValue())); assertEquals(df.format(BigDecimal.valueOf(1.60)), df.format(BigDecimal.valueOf(1.60).doubleValue())); assertEquals(df.format(BigDecimal.valueOf(15)), - df.format(BigDecimal.valueOf(15).doubleValue())); + df.format(BigDecimal.valueOf(15).doubleValue())); assertEquals(df.format(BigDecimal.valueOf(170)), - df.format(BigDecimal.valueOf(170).doubleValue())); + df.format(BigDecimal.valueOf(170).doubleValue())); assertEquals(df.format(BigDecimal.valueOf(234.56)), - df.format(BigDecimal.valueOf(234.56).doubleValue())); + df.format(BigDecimal.valueOf(234.56).doubleValue())); assertEquals(df.format(BigDecimal.valueOf(0)), df.format(BigDecimal.valueOf(0).doubleValue())); assertEquals(df.format(BigDecimal.valueOf(-1)), @@ -144,11 +146,11 @@ public class DecimalFormatTest extends junit.framework.TestCase { assertEquals(df.format(BigDecimal.valueOf(-10000)), df.format(BigDecimal.valueOf(-10000).doubleValue())); assertEquals(df.format(BigDecimal.valueOf(-0.001)), - df.format(BigDecimal.valueOf(-0.001).doubleValue())); + df.format(BigDecimal.valueOf(-0.001).doubleValue())); assertEquals(df.format(BigDecimal.valueOf(1234567890.1234567)), - df.format(BigDecimal.valueOf(1234567890.1234567).doubleValue())); + df.format(BigDecimal.valueOf(1234567890.1234567).doubleValue())); assertEquals(df.format(BigDecimal.valueOf(1.234567E100)), - df.format(BigDecimal.valueOf(1.234567E100).doubleValue())); + df.format(BigDecimal.valueOf(1.234567E100).doubleValue())); } private void assertBigDecimalWithFraction(BigDecimal bd, String expectedResult, int fraction) { @@ -197,4 +199,123 @@ public class DecimalFormatTest extends junit.framework.TestCase { df.setCurrency(Currency.getInstance("CHF")); df.setCurrency(Currency.getInstance("GBP")); } + + // Check we don't crash on null inputs. + public void testBug15081434() throws Exception { + DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance(Locale.US); + try { + df.parse(null); + fail(); + } catch (NullPointerException expected) { + } + + try { + df.applyLocalizedPattern(null); + fail(); + } catch (NullPointerException expected) { + } + + try { + df.applyPattern(null); + fail(); + } catch (NullPointerException expected) { + } + + try { + df.applyPattern(null); + fail(); + } catch (NullPointerException expected) { + } + + try { + df.format(null, new StringBuffer(), new FieldPosition(0)); + fail(); + } catch (IllegalArgumentException expected) { + } + + try { + df.parse(null, new ParsePosition(0)); + fail(); + } catch (NullPointerException expected) { + } + + // This just ignores null. + df.setDecimalFormatSymbols(null); + + try { + df.setCurrency(null); + fail(); + } catch (NullPointerException expected) { + } + + // These just ignore null. + df.setNegativePrefix(null); + df.setNegativeSuffix(null); + df.setPositivePrefix(null); + df.setPositiveSuffix(null); + + try { + df.setRoundingMode(null); + fail(); + } catch (NullPointerException expected) { + } + } + + // Confirm the fraction digits do not change when the currency is changed. + public void testBug71369() { + final String nonBreakingSpace = "\u00A0"; + + NumberFormat numberFormat = NumberFormat.getCurrencyInstance(Locale.GERMAN); + numberFormat.setCurrency(Currency.getInstance("USD")); + + assertEquals("2,01" + nonBreakingSpace + "$", numberFormat.format(2.01)); + + numberFormat.setMinimumFractionDigits(0); + numberFormat.setMaximumFractionDigits(0); + + String expected = "2" + nonBreakingSpace + "$"; + assertEquals(expected, numberFormat.format(2.01)); + + // Changing the currency must not reset the digits. + numberFormat.setCurrency(Currency.getInstance("EUR")); + numberFormat.setCurrency(Currency.getInstance("USD")); + + assertEquals(expected, numberFormat.format(2.01)); + } + + // Confirm the currency symbol used by a format is determined by the locale of the format + // not the current default Locale. + public void testSetCurrency_symbolOrigin() { + Currency currency = Currency.getInstance("CNY"); + Locale locale1 = Locale.CHINA; + Locale locale2 = Locale.US; + String locale1Symbol = currency.getSymbol(locale1); + String locale2Symbol = currency.getSymbol(locale2); + // This test only works if we can tell where the symbol came from, which requires they are + // different across the two locales chosen. + assertFalse(locale1Symbol.equals(locale2Symbol)); + + Locale originalLocale = Locale.getDefault(); + try { + Locale.setDefault(locale1); + String amountDefaultLocale1 = + formatArbitraryCurrencyAmountInLocale(currency, locale2); + + Locale.setDefault(locale2); + String amountDefaultLocale2 = + formatArbitraryCurrencyAmountInLocale(currency, locale2); + + // This used to fail because Currency.getSymbol() was used without providing the + // format's locale. + assertEquals(amountDefaultLocale1, amountDefaultLocale2); + } finally { + Locale.setDefault(originalLocale); + } + } + + private String formatArbitraryCurrencyAmountInLocale(Currency currency, Locale locale) { + NumberFormat localeCurrencyFormat = NumberFormat.getCurrencyInstance(locale); + localeCurrencyFormat.setCurrency(currency); + return localeCurrencyFormat.format(1000); + } } diff --git a/luni/src/test/java/libcore/java/text/NumberFormatTest.java b/luni/src/test/java/libcore/java/text/NumberFormatTest.java index 1a14462..4ff063b 100644 --- a/luni/src/test/java/libcore/java/text/NumberFormatTest.java +++ b/luni/src/test/java/libcore/java/text/NumberFormatTest.java @@ -66,16 +66,16 @@ public class NumberFormatTest extends junit.framework.TestCase { public void test_getIntegerInstance_ar() throws Exception { NumberFormat numberFormat = NumberFormat.getNumberInstance(new Locale("ar")); - assertEquals("#0.###;#0.###-", ((DecimalFormat) numberFormat).toPattern()); + assertEquals("#,##0.###", ((DecimalFormat) numberFormat).toPattern()); NumberFormat integerFormat = NumberFormat.getIntegerInstance(new Locale("ar")); - assertEquals("#0;#0-", ((DecimalFormat) integerFormat).toPattern()); + assertEquals("#,##0", ((DecimalFormat) integerFormat).toPattern()); } public void test_numberLocalization() throws Exception { Locale arabic = new Locale("ar"); NumberFormat nf = NumberFormat.getNumberInstance(arabic); assertEquals('\u0660', new DecimalFormatSymbols(arabic).getZeroDigit()); - assertEquals("١٢٣٤٥٦٧٨٩٠", nf.format(1234567890)); + assertEquals("١٬٢٣٤٬٥٦٧٬٨٩٠", nf.format(1234567890)); } // Formatting percentages is confusing but deliberate. @@ -90,4 +90,40 @@ public class NumberFormatTest extends junit.framework.TestCase { } catch (IllegalArgumentException expected) { } } + + public void test_62269() throws Exception { + NumberFormat nf = NumberFormat.getNumberInstance(Locale.US); + try { + nf.parse(null); + fail(); + } catch (NullPointerException expected) { + } + } + + public void test_nullLocales() { + try { + NumberFormat.getInstance(null); + fail(); + } catch (NullPointerException expected) {} + + try { + NumberFormat.getIntegerInstance(null); + fail(); + } catch (NullPointerException expected) {} + + try { + NumberFormat.getCurrencyInstance(null); + fail(); + } catch (NullPointerException expected) {} + + try { + NumberFormat.getPercentInstance(null); + fail(); + } catch (NullPointerException expected) {} + + try { + NumberFormat.getNumberInstance(null); + fail(); + } catch (NullPointerException expected) {} + } } diff --git a/luni/src/test/java/libcore/java/text/OldBidiTest.java b/luni/src/test/java/libcore/java/text/OldBidiTest.java index 2e5fd21..45fe258 100644 --- a/luni/src/test/java/libcore/java/text/OldBidiTest.java +++ b/luni/src/test/java/libcore/java/text/OldBidiTest.java @@ -22,11 +22,9 @@ import junit.framework.TestCase; public class OldBidiTest extends TestCase { - Bidi bd; - public void testToString() { try { - bd = new Bidi("bidi", 173); + Bidi bd = new Bidi("bidi", 173); assertNotNull("Bidi representation is null", bd.toString()); } catch (Exception e) { fail("Unexpected exception " + e.toString()); @@ -41,7 +39,7 @@ public class OldBidiTest extends TestCase { } public void testGetRunLevelLInt() { - bd = new Bidi("text", Bidi.DIRECTION_LEFT_TO_RIGHT); + Bidi bd = new Bidi("text", Bidi.DIRECTION_LEFT_TO_RIGHT); try { assertEquals(0, bd.getRunLevel(0)); assertEquals(0, bd.getRunLevel(bd.getRunCount())); @@ -65,25 +63,11 @@ public class OldBidiTest extends TestCase { } public void testGetRunStart() { - bd = new Bidi(new char[] { 's', 's', 's' }, 0, new byte[] { (byte) -7, + Bidi bd = new Bidi(new char[] { 's', 's', 's' }, 0, new byte[] { (byte) -7, (byte) -2, (byte) 3 }, 0, 3, Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT); assertEquals(0, bd.getRunStart(0)); assertEquals(1, bd.getRunStart(1)); assertEquals(2, bd.getRunStart(2)); - - String LTR = "\u0061\u0062"; - String RTL = "\u05DC\u05DD"; - String newLine = "\n"; - String defText = LTR + newLine + RTL + LTR + RTL; - - int[][] expectedRuns = { { 0, 3 }, { 3, 5 }, { 5, 7 }, { 7, 9 }, }; - - Bidi bi = new Bidi(defText, 0); - - final int count = bi.getRunCount(); - for (int i = 0; i < count; i++) { - assertEquals(expectedRuns[i][0], bi.getRunStart(i)); - } } } diff --git a/luni/src/test/java/libcore/java/text/OldCollationElementIteratorTest.java b/luni/src/test/java/libcore/java/text/OldCollationElementIteratorTest.java deleted file mode 100644 index 9e98a56..0000000 --- a/luni/src/test/java/libcore/java/text/OldCollationElementIteratorTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.text; - -import java.text.CollationElementIterator; -import java.text.Collator; -import java.text.RuleBasedCollator; -import java.util.Locale; -import junit.framework.TestCase; - -public class OldCollationElementIteratorTest extends TestCase { - - public void testPrevious() { - RuleBasedCollator coll = (RuleBasedCollator) Collator.getInstance(Locale.US); - String text = "abc"; - CollationElementIterator iterator = coll - .getCollationElementIterator(text); - int[] orders = new int[text.length()]; - int order = iterator.next(); - int i = 0; - while (order != CollationElementIterator.NULLORDER) { - orders[i++] = order; - order = iterator.next(); - } - - int offset = iterator.getOffset(); - assertEquals(text.length(), offset); - order = iterator.previous(); - - while (order != CollationElementIterator.NULLORDER) { - assertEquals(orders[--i], order); - order = iterator.previous(); - } - - assertEquals(0, iterator.getOffset()); - } -} diff --git a/luni/src/test/java/libcore/java/text/OldCollationKeyTest.java b/luni/src/test/java/libcore/java/text/OldCollationKeyTest.java index 1fc8264..eea5246 100644 --- a/luni/src/test/java/libcore/java/text/OldCollationKeyTest.java +++ b/luni/src/test/java/libcore/java/text/OldCollationKeyTest.java @@ -24,7 +24,7 @@ import java.text.RuleBasedCollator; public class OldCollationKeyTest extends junit.framework.TestCase { - public void test_toByteArray() { + public void test_toByteArray() throws ParseException { // Test for method byte [] java.text.CollationKey.toByteArray() Collator collator = Collator.getInstance(); collator.setStrength(Collator.PRIMARY); @@ -32,12 +32,7 @@ public class OldCollationKeyTest extends junit.framework.TestCase { byte[] bytes = key1.toByteArray(); assertTrue("Not enough bytes", bytes.length >= 3); - try { - collator = new RuleBasedCollator("= 1 , 2 ; 3 , 4 < 5 ; 6 , 7"); - } catch (ParseException e) { - fail("ParseException"); - return; - } + collator = new RuleBasedCollator("&0 = 1 , 2 ; 3 , 4 < 5 ; 6 , 7"); /* * CollationElementIterator it = * ((RuleBasedCollator)collator).getCollationElementIterator("1234567"); diff --git a/luni/src/test/java/libcore/java/text/OldDecimalFormatTest.java b/luni/src/test/java/libcore/java/text/OldDecimalFormatTest.java deleted file mode 100644 index f3e016e..0000000 --- a/luni/src/test/java/libcore/java/text/OldDecimalFormatTest.java +++ /dev/null @@ -1,1007 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.text; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.text.AttributedCharacterIterator; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.text.FieldPosition; -import java.text.NumberFormat; -import java.text.ParseException; -import java.text.ParsePosition; -import java.util.BitSet; -import java.util.Locale; -import junit.framework.TestCase; -import tests.support.Support_DecimalFormat; - -public class OldDecimalFormatTest extends TestCase { - - public void test_formatToCharacterIterator() throws Exception { - AttributedCharacterIterator iterator; - int[] runStarts; - int[] runLimits; - String result; - char current; - - // For BigDecimal with multiplier test. - DecimalFormat df = new DecimalFormat(); - df.setMultiplier(10); - iterator = df.formatToCharacterIterator(new BigDecimal("12345678901234567890")); - result = "123,456,789,012,345,678,900"; - current = iterator.current(); - for (int i = 0; i < result.length(); i++) { - assertEquals("wrong char @" + i, result.charAt(i), current); - current = iterator.next(); - } - - // For BigDecimal with multiplier test. - df = new DecimalFormat(); - df.setMultiplier(-1); - df.setMaximumFractionDigits(20); - iterator = df.formatToCharacterIterator(new BigDecimal("1.23456789012345678901")); - result = "-1.23456789012345678901"; - current = iterator.current(); - for (int i = 0; i < result.length(); i++) { - assertEquals("wrong char @" + i, result.charAt(i), current); - current = iterator.next(); - } - - iterator = new DecimalFormat() - .formatToCharacterIterator(new BigDecimal("1.23456789E1234")); - runStarts = new int[] {0, 0, 2, 3, 3, 3, 6, 7, 7, 7, 10, 11, 11, 11, 14}; - runLimits = new int[] {2, 2, 3, 6, 6, 6, 7, 10, 10, 10, 11, 14, 14, 14, 15}; - result = "12,345,678,900,"; // 000,000,000,000.... - current = iterator.current(); - for (int i = 0; i < runStarts.length; i++) { - assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart()); - assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit()); - assertEquals("wrong char @" + i, result.charAt(i), current); - current = iterator.next(); - } - assertEquals(0, iterator.getBeginIndex()); - assertEquals(1646, iterator.getEndIndex()); - - iterator = new DecimalFormat() - .formatToCharacterIterator(new BigDecimal("1.23456789E301")); - runStarts = new int[] {0, 0, 2, 3, 3, 3, 6, 7, 7, 7, 10, 11, 11, 11, 14}; - runLimits = new int[] {2, 2, 3, 6, 6, 6, 7, 10, 10, 10, 11, 14, 14, 14, 15}; - result = "12,345,678,900,"; // 000,000,000,000.... - current = iterator.current(); - for (int i = 0; i < runStarts.length; i++) { - assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart()); - assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit()); - assertEquals("wrong char @" + i, result.charAt(i), current); - current = iterator.next(); - } - assertEquals(0, iterator.getBeginIndex()); - assertEquals(402, iterator.getEndIndex()); - - iterator = new DecimalFormat() - .formatToCharacterIterator(new BigDecimal("1.2345678E4")); - runStarts = new int[] {0, 0, 2, 3, 3, 3, 6, 7, 7, 7}; - runLimits = new int[] {2, 2, 3, 6, 6, 6, 7, 10, 10, 10}; - result = "12,345.678"; - current = iterator.current(); - for (int i = 0; i < runStarts.length; i++) { - assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart()); - assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit()); - assertEquals("wrong char @" + i, result.charAt(i), current); - current = iterator.next(); - } - assertEquals(0, iterator.getBeginIndex()); - assertEquals(10, iterator.getEndIndex()); - - iterator = new DecimalFormat() - .formatToCharacterIterator(new BigInteger("123456789")); - runStarts = new int[] {0, 0, 0, 3, 4, 4, 4, 7, 8, 8, 8}; - runLimits = new int[] {3, 3, 3, 4, 7, 7, 7, 8, 11, 11, 11}; - result = "123,456,789"; - current = iterator.current(); - for (int i = 0; i < runStarts.length; i++) { - assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart()); - assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit()); - assertEquals("wrong char @" + i, result.charAt(i), current); - current = iterator.next(); - } - assertEquals(0, iterator.getBeginIndex()); - assertEquals(11, iterator.getEndIndex()); - } - - /* - * Test the getter and setter of parseBigDecimal and parseIntegerOnly and - * test the default value of them. - */ - public void test_isParseBigDecimalLjava_lang_Boolean_isParseIntegerOnlyLjava_lang_Boolean() { - - // parseBigDecimal default to false - DecimalFormat form = (DecimalFormat) DecimalFormat - .getInstance(Locale.US); - assertFalse(form.isParseBigDecimal()); - form.setParseBigDecimal(true); - assertTrue(form.isParseBigDecimal()); - - try { - Number result = form.parse("123.123"); - assertEquals(new BigDecimal("123.123"), result); - } catch (ParseException e) { - fail("ParseException was thrown."); - } - - form.setParseBigDecimal(false); - assertFalse(form.isParseBigDecimal()); - - try { - Number result = form.parse("123.123"); - assertFalse(result instanceof BigDecimal); - } catch (ParseException e) { - fail("ParseException was thrown."); - } - - // parseIntegerOnly default to false - assertFalse(form.isParseIntegerOnly()); - } - - public void test_isParseIntegerOnly() { - - DecimalFormat format = new DecimalFormat(); - assertFalse("Default value of isParseIntegerOnly is true", - format.isParseIntegerOnly()); - - format.setParseIntegerOnly(true); - assertTrue(format.isParseIntegerOnly()); - try { - Number result = format.parse("123.123"); - assertEquals(new Long("123"), result); - } catch (ParseException e) { - fail("ParseException was thrown."); - } - - format.setParseIntegerOnly(false); - assertFalse(format.isParseIntegerOnly()); - try { - Number result = format.parse("123.123"); - assertEquals(new Double("123.123"), result); - } catch (ParseException e) { - fail("ParseException was thrown."); - } - } - - public void test_isGroupingUsed() { - String [] patterns = {"####.##", "######.######", "000000.000000", - "######.000000", "000000.######", " ###.###", "$#####.######", - "$$####.######"}; - - for(String pattern:patterns) { - DecimalFormat format = new DecimalFormat(pattern); - assertFalse(format.isGroupingUsed()); - } - - DecimalFormat format = new DecimalFormat("###,####"); - assertTrue(format.isGroupingUsed()); - } - - // Test the type of the returned object - public void test_parseLjava_lang_String_Ljava_text_ParsePosition() { - DecimalFormat form = (DecimalFormat) DecimalFormat.getInstance(Locale.US); - form.setParseIntegerOnly(true); - form.setParseBigDecimal(true); - - final String doubleMax2 = "359,538,626,972,463,141,629,054,847,463,408," - + "713,596,141,135,051,689,993,197,834,953,606,314,521,560,057,077," - + "521,179,117,265,533,756,343,080,917,907,028,764,928,468,642,653," - + "778,928,365,536,935,093,407,075,033,972,099,821,153,102,564,152," - + "490,980,180,778,657,888,151,737,016,910,267,884,609,166,473,806," - + "445,896,331,617,118,664,246,696,549,595,652,408,289,446,337,476," - + "354,361,838,599,762,500,808,052,368,249,716,736"; - Number number = form.parse(doubleMax2, new ParsePosition(0)); - assertTrue(number instanceof BigDecimal); - BigDecimal result = (BigDecimal)number; - assertEquals(new BigDecimal(Double.MAX_VALUE).add(new BigDecimal( - Double.MAX_VALUE)), result); - } - - // AndroidOnly: Difference to RI - public void test_getMaximumIntegerDigits_AndroidOnly() { - final int maxIntDigit = 309; - - // When use default locale, in this case zh_CN - // the returned instance of NumberFormat is a DecimalFormat - DecimalFormat form = new DecimalFormat("00.###E0"); - NumberFormat nform = DecimalFormat.getInstance(Locale.US); - nform = DecimalFormat.getInstance(Locale.US); - form = null; - if (nform instanceof DecimalFormat) { - form = (DecimalFormat) nform; - } - // getMaximumIntegerDigits from NumberFormat default to 309 - // getMaximumIntegerDigits from DecimalFormat default to 309 - // the following 2 assertions will fail on RI implementation, since the - // implementation of ICU and RI are not identical. RI does not give - // DecimalFormat an initial bound about its maximumIntegerDigits - // (default to Integer.MAX_VALUE: 2147483647 ) - assertEquals(maxIntDigit, nform.getMaximumIntegerDigits()); - assertEquals(maxIntDigit, form.getMaximumIntegerDigits()); - } - - // AndroidOnly: second 0 needs to be quoted in icu. - // (quoting special characters in prefix and suffix necessary) - public void test_getMaximumIntegerDigits2() { - // regression test for HARMONY-878 - assertTrue(new DecimalFormat("0\t'0'").getMaximumIntegerDigits() > 0); - } - - public void test_setPositivePrefixLjava_lang_String() { - DecimalFormat format = new DecimalFormat(); - assertEquals("", format.getPositivePrefix()); - - format.setPositivePrefix("PosPrf"); - assertEquals("PosPrf", format.getPositivePrefix()); - try { - assertTrue(format.parse("PosPrf123.45").doubleValue() == 123.45); - } catch(java.text.ParseException pe) { - fail("ParseException was thrown."); - } - - format.setPositivePrefix(""); - assertEquals("", format.getPositivePrefix()); - - format.setPositivePrefix(null); - assertNull(format.getPositivePrefix()); - } - public void test_setPositiveSuffixLjava_lang_String() { - DecimalFormat format = new DecimalFormat(); - assertEquals("", format.getPositiveSuffix()); - - format.setPositiveSuffix("PosSfx"); - assertEquals("PosSfx", format.getPositiveSuffix()); - try { - assertTrue(format.parse("123.45PosSfx").doubleValue() == 123.45); - } catch(java.text.ParseException pe) { - fail("ParseException was thrown."); - } - - format.setPositiveSuffix(""); - assertEquals("", format.getPositiveSuffix()); - - format.setPositiveSuffix(null); - assertNull(format.getPositiveSuffix()); - } - public void test_setNegativePrefixLjava_lang_String() { - DecimalFormat format = new DecimalFormat(); - assertEquals("-", format.getNegativePrefix()); - - format.setNegativePrefix("NegPrf"); - assertEquals("NegPrf", format.getNegativePrefix()); - try { - assertTrue(format.parse("NegPrf123.45").doubleValue() == -123.45); - } catch(java.text.ParseException pe) { - fail("ParseException was thrown."); - } - format.setNegativePrefix(""); - assertEquals("", format.getNegativePrefix()); - - format.setNegativePrefix(null); - assertNull(format.getNegativePrefix()); - } - public void test_setNegativeSuffixLjava_lang_String() { - DecimalFormat format = new DecimalFormat(); - assertEquals("", format.getNegativeSuffix()); - - format.setNegativeSuffix("NegSfx"); - assertEquals("NegSfx", format.getNegativeSuffix()); - try { - assertTrue(format.parse("123.45NegPfx").doubleValue() == 123.45); - } catch(java.text.ParseException pe) { - fail("ParseException was thrown."); - } - - format.setNegativeSuffix(""); - assertEquals("", format.getNegativeSuffix()); - - format.setNegativeSuffix(null); - assertNull(format.getNegativeSuffix()); - } - - public void test_toLocalizedPattern() { - DecimalFormat format = new DecimalFormat(); - format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); - try { - format.applyLocalizedPattern("#.#"); - assertEquals("Wrong pattern 1", "#0.#", format.toLocalizedPattern()); - format.applyLocalizedPattern("#."); - assertEquals("Wrong pattern 2", "#0.", format.toLocalizedPattern()); - format.applyLocalizedPattern("#"); - assertEquals("Wrong pattern 3", "#", format.toLocalizedPattern()); - format.applyLocalizedPattern(".#"); - assertEquals("Wrong pattern 4", "#.0", format.toLocalizedPattern()); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - public void test_toPattern() { - DecimalFormat format = new DecimalFormat(); - try { - format.applyPattern("#.#"); - assertEquals("Wrong pattern 1", "#0.#", format.toPattern()); - format.applyPattern("#."); - assertEquals("Wrong pattern 2", "#0.", format.toPattern()); - format.applyPattern("#"); - assertEquals("Wrong pattern 3", "#", format.toPattern()); - format.applyPattern(".#"); - assertEquals("Wrong pattern 4", "#.0", format.toPattern()); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - public void test_setGroupingUse() { - DecimalFormat format = new DecimalFormat(); - - StringBuffer buf = new StringBuffer(); - format.setGroupingUsed(false); - format.format(new Long(1970), buf, new FieldPosition(0)); - assertEquals("1970", buf.toString()); - assertFalse(format.isGroupingUsed()); - format.format(new Long(1970), buf, new FieldPosition(0)); - assertEquals("19701970", buf.toString()); - assertFalse(format.isGroupingUsed()); - - format.setGroupingUsed(true); - format.format(new Long(1970), buf, new FieldPosition(0)); - assertEquals("197019701,970", buf.toString()); - assertTrue(format.isGroupingUsed()); - } - - public void test_Constructor() { - // Test for method java.text.DecimalFormat() - // the constructor form that specifies a pattern is equal to the form - // constructed with no pattern and applying that pattern using the - // applyPattern call - try { - DecimalFormat format1 = new DecimalFormat(); - format1.applyPattern("'$'1000.0000"); - DecimalFormat format2 = new DecimalFormat(); - format2.applyPattern("'$'1000.0000"); - assertTrue( - "Constructed format did not match applied format object", - format2.equals(format1)); - DecimalFormat format3 = new DecimalFormat("'$'1000.0000"); - assertTrue( - "Constructed format did not match applied format object", - format3.equals(format1)); - DecimalFormat format4 = new DecimalFormat("'$'8000.0000"); - assertTrue( - "Constructed format did not match applied format object", - !format4.equals(format1)); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - public void test_ConstructorLjava_lang_String() { - // Test for method java.text.DecimalFormat(java.lang.String) - // the constructor form that specifies a pattern is equal to the form - // constructed with no pattern and applying that pattern using the - // applyPattern call - DecimalFormat format = new DecimalFormat("'$'0000.0000"); - DecimalFormat format1 = new DecimalFormat(); - format1.applyPattern("'$'0000.0000"); - assertTrue("Constructed format did not match applied format object", - format.equals(format1)); - - String [] patterns = {"####.##", "######.######", "000000.000000", - "######.000000", "000000.######", " ###.###", "$#####.######", - "$$####.######", "%#,##,###,####", "#,##0.00;(#,##0.00)"}; - - for(String str:patterns) { - new DecimalFormat(str); - } - - try { - new DecimalFormat(null); - fail("NullPointerException wasn't thrown."); - } catch(NullPointerException npe){ - //expected - } - - String [] incPatterns = {"%#,##,###,####'", "#.##0.00"}; - for(String str:incPatterns) { - try { - new DecimalFormat(str); - fail("IllegalArgumentException wasn't thrown for pattern: " + str); - } catch(IllegalArgumentException iae){ - //expected - } - } - } - - /** - * Case 1: Try to construct object using correct pattern and fromat symbols. - * Case 2: Try to construct object using null arguments. - * Case 3: Try to construct object using incorrect pattern. - */ - public void test_ConstructorLjava_lang_StringLjava_text_DecimalFormatSymbols() { - try { - // case 1: Try to construct object using correct pattern and fromat - // symbols. - DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.CANADA); - DecimalFormat format1 = new DecimalFormat("'$'1000.0000", dfs); - DecimalFormat format2 = new DecimalFormat(); - format2.applyPattern("'$'1000.0000"); - format2.setDecimalFormatSymbols(dfs); - assertTrue( - "Constructed format did not match applied format object", - format2.equals(format1)); - assertTrue( - "Constructed format did not match applied format object", - !format1.equals(new DecimalFormat("'$'1000.0000", - new DecimalFormatSymbols(Locale.CHINA)))); - - // case 2: Try to construct object using null arguments. - try { - new DecimalFormat("'$'1000.0000", (DecimalFormatSymbols) null); - fail("Expected NullPointerException was not thrown"); - } catch (NullPointerException e) { - // expected - } - try { - new DecimalFormat(null, new DecimalFormatSymbols()); - fail("Expected NullPointerException was not thrown"); - } catch (NullPointerException e) { - // expected - } - try { - new DecimalFormat(null, (DecimalFormatSymbols) null); - fail("Expected NullPointerException was not thrown"); - } catch (NullPointerException e) { - // expected - } - - // case 3: Try to construct object using incorrect pattern. - try { - new DecimalFormat("$'", new DecimalFormatSymbols()); - fail("Expected IllegalArgumentException was not thrown"); - } catch (IllegalArgumentException e) { - // expected - } - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - /** - * Case 1: Try to apply correct variants of pattern. - * Case 2: Try to apply malformed patten. Case 3: Try to apply null pattern. - */ - public void test_applyLocalizedPatternLjava_lang_String() { - DecimalFormat format = new DecimalFormat(); - try { - // case 1: Try to apply correct variants of pattern. - format.applyLocalizedPattern("#.#"); - assertEquals("Wrong pattern 1", "#0.#", format.toLocalizedPattern()); - format.applyLocalizedPattern("#."); - assertEquals("Wrong pattern 2", "#0.", format.toLocalizedPattern()); - format.applyLocalizedPattern("#"); - assertEquals("Wrong pattern 3", "#", format.toLocalizedPattern()); - format.applyLocalizedPattern(".#"); - assertEquals("Wrong pattern 4", "#.0", format.toLocalizedPattern()); - - // case 2: Try to apply malformed patten. - try { - format.applyLocalizedPattern("'#,#:#0.0#;(#)"); - fail("Expected IllegalArgumentException was not thrown"); - } catch (IllegalArgumentException e) { - // expected - } - - // case 3: Try to apply null patern. - try { - format.applyLocalizedPattern((String) null); - fail("Expected NullPointerException was not thrown"); - } catch (NullPointerException e) { - // expected - } - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - public void test_applyPatternLjava_lang_String() { - DecimalFormat format = new DecimalFormat("#.#"); - assertEquals("Wrong pattern 1", "#0.#", format.toPattern()); - format = new DecimalFormat("#."); - assertEquals("Wrong pattern 2", "#0.", format.toPattern()); - format = new DecimalFormat("#"); - assertEquals("Wrong pattern 3", "#", format.toPattern()); - format = new DecimalFormat(".#"); - assertEquals("Wrong pattern 4", "#.0", format.toPattern()); - - DecimalFormat decFormat = new DecimalFormat("#.#"); - - try { - decFormat.applyPattern(null); - fail("NullPointerException was not thrown."); - } catch(NullPointerException npe) { - //expected - } - - String [] incPatterns = {"%#,##,###,####'", "#.##0.00"}; - for(String str:incPatterns) { - try { - decFormat.applyPattern(str); - fail("IllegalArgumentException was not thrown for pattern: " + - str); - } catch(IllegalArgumentException iae) { - //expected - } - } - } - - // AndroidOnly: icu supports 2 grouping sizes - public void test_applyPatternLjava_lang_String2() { - DecimalFormat decFormat = new DecimalFormat("#.#"); - String [] patterns = {"####.##", "######.######", "000000.000000", - "######.000000", "000000.######", " ###.###", "$#####.######", - "$$####.######", "%#,##,###,####", "#,##0.00;(#,##0.00)", - "##.##-E"}; - - String [] expResult = {"#0.##", "#0.######", "#000000.000000", - "#.000000", "#000000.######", " #0.###", "$#0.######", - "$$#0.######", - "%#,###,####", // icu only. icu supports two grouping sizes - "#,##0.00;(#,##0.00)", - "#0.##-'E'"}; // icu only. E in the suffix does not need to be - // quoted. This is done automatically. - - for (int i = 0; i < patterns.length; i++) { - decFormat.applyPattern(patterns[i]); - String result = decFormat.toPattern(); - assertEquals("Failed to apply following pattern: " + patterns[i] + - " expected: " + expResult[i] + " returned: " + result, - expResult[i], result); - } - } - - public void test_clone() { - DecimalFormat format = (DecimalFormat) DecimalFormat - .getInstance(Locale.US); - DecimalFormat cloned = (DecimalFormat) format.clone(); - assertEquals(cloned.getDecimalFormatSymbols(), format - .getDecimalFormatSymbols()); - - format = new DecimalFormat("'$'0000.0000"); - DecimalFormat format1 = (DecimalFormat) (format.clone()); - // make sure the objects are equal - assertTrue("Object's clone isn't equal!", format.equals(format1)); - // change the content of the clone and make sure it's not equal anymore - // verifies that it's data is now distinct from the original - format1.applyPattern("'$'0000.####"); - assertTrue("Object's changed clone should not be equal!", !format - .equals(format1)); - } - - private void compare(String testName, String format, String expected) { - assertTrue(testName + " got: " + format + " expected: " + expected, - format.equals(expected)); - } - - private boolean compare(int count, String format, String expected) { - boolean result = format.equals(expected); - if (!result) - System.out.println("Failure test: " + count + " got: " + format - + " expected: " + expected); - return result; - } - - public void test_formatDLjava_lang_StringBufferLjava_text_FieldPosition() { - new Support_DecimalFormat( - "test_formatDLjava_lang_StringBufferLjava_text_FieldPosition") - .t_format_with_FieldPosition(); - - int failCount = 0; - BitSet failures = new BitSet(); - - final DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US); - - DecimalFormat df = new DecimalFormat("00.0#E0", dfs); - compare("00.0#E0: 0.0", df.format(0.0), "00.0E0"); - compare("00.0#E0: 1.0", df.format(1.0), "10.0E-1"); - compare("00.0#E0: 12.0", df.format(12.0), "12.0E0"); - compare("00.0#E0: 123.0", df.format(123.0), "12.3E1"); - compare("00.0#E0: 1234.0", df.format(1234.0), "12.34E2"); - compare("00.0#E0: 12346.0", df.format(12346.0), "12.35E3"); - compare("00.0#E0: 99999.0", df.format(99999.0), "10.0E4"); - compare("00.0#E0: 1.2", df.format(1.2), "12.0E-1"); - compare("00.0#E0: 12.3", df.format(12.3), "12.3E0"); - compare("00.0#E0: 123.4", df.format(123.4), "12.34E1"); - compare("00.0#E0: 1234.6", df.format(1234.6), "12.35E2"); - compare("00.0#E0: 9999.9", df.format(9999.9), "10.0E3"); - compare("00.0#E0: 0.1", df.format(0.1), "10.0E-2"); - compare("00.0#E0: 0.12", df.format(0.12), "12.0E-2"); - compare("00.0#E0: 0.123", df.format(0.123), "12.3E-2"); - compare("00.0#E0: 0.1234", df.format(0.1234), "12.34E-2"); - compare("00.0#E0: 0.12346", df.format(0.12346), "12.35E-2"); - compare("00.0#E0: 0.99999", df.format(0.99999), "10.0E-1"); - compare("00.0#E0: -0.0", df.format(-0.0), "-00.0E0"); - compare("00.0#E0: -1.0", df.format(-1.0), "-10.0E-1"); - compare("00.0#E0: -12.0", df.format(-12.0), "-12.0E0"); - compare("00.0#E0: -123.0", df.format(-123.0), "-12.3E1"); - compare("00.0#E0: -1234.0", df.format(-1234.0), "-12.34E2"); - compare("00.0#E0: -12346.0", df.format(-12346.0), "-12.35E3"); - compare("00.0#E0: -99999.0", df.format(-99999.0), "-10.0E4"); - - df = new DecimalFormat("##0.0E0", dfs); - compare("##0.0E0: -0.0", df.format(-0.0), "-0.0E0"); - compare("##0.0E0: 0.0", df.format(0.0), "0.0E0"); - compare("##0.0E0: 1.0", df.format(1.0), "1.0E0"); - compare("##0.0E0: 12.0", df.format(12.0), "12E0"); - compare("##0.0E0: 123.0", df.format(123.0), "123E0"); // Android fails, here! - compare("##0.0E0: 1234.0", df.format(1234.0), "1.234E3"); - compare("##0.0E0: 12346.0", df.format(12346.0), "12.35E3"); - // Fails in JDK 1.2.2 - if (!compare(failCount, df.format(99999.0), "100E3")) - failures.set(failCount); - failCount++; - compare("##0.0E0: 999999.0", df.format(999999.0), "1.0E6"); - - df = new DecimalFormat("#00.0##E0", dfs); - compare("#00.0##E0: 0.1", df.format(0.1), "100E-3"); - compare("#00.0##E0: 0.12", df.format(0.12), "120E-3"); - compare("#00.0##E0: 0.123", df.format(0.123), "123E-3"); - compare("#00.0##E0: 0.1234", df.format(0.1234), "123.4E-3"); - compare("#00.0##E0: 0.1234567", df.format(0.1234567), "123.457E-3"); - compare("#00.0##E0: 0.01", df.format(0.01), "10.0E-3"); - compare("#00.0##E0: 0.012", df.format(0.012), "12.0E-3"); - compare("#00.0##E0: 0.0123", df.format(0.0123), "12.3E-3"); - compare("#00.0##E0: 0.01234", df.format(0.01234), "12.34E-3"); - compare("#00.0##E0: 0.01234567", df.format(0.01234567), "12.3457E-3"); - compare("#00.0##E0: 0.001", df.format(0.001), "1.00E-3"); - compare("#00.0##E0: 0.0012", df.format(0.0012), "1.20E-3"); - compare("#00.0##E0: 0.00123", df.format(0.00123), "1.23E-3"); - compare("#00.0##E0: 0.001234", df.format(0.001234), "1.234E-3"); - compare("#00.0##E0: 0.001234567", df.format(0.001234567), "1.23457E-3"); - compare("#00.0##E0: 0.0001", df.format(0.0001), "100E-6"); - compare("#00.0##E0: 0.00012", df.format(0.00012), "120E-6"); - compare("#00.0##E0: 0.000123", df.format(0.000123), "123E-6"); - compare("#00.0##E0: 0.0001234", df.format(0.0001234), "123.4E-6"); - compare("#00.0##E0: 0.0001234567", df.format(0.0001234567), - "123.457E-6"); - - // Fails in JDK 1.2.2 - if (!compare(failCount, df.format(0.0), "0.00E0")) - failures.set(failCount); - failCount++; - compare("#00.0##E0: 1.0", df.format(1.0), "1.00E0"); - compare("#00.0##E0: 12.0", df.format(12.0), "12.0E0"); - compare("#00.0##E0: 123.0", df.format(123.0), "123E0"); - compare("#00.0##E0: 1234.0", df.format(1234.0), "1.234E3"); - compare("#00.0##E0: 12345.0", df.format(12345.0), "12.345E3"); - compare("#00.0##E0: 123456.0", df.format(123456.0), "123.456E3"); - compare("#00.0##E0: 1234567.0", df.format(1234567.0), "1.23457E6"); - compare("#00.0##E0: 12345678.0", df.format(12345678.0), "12.3457E6"); - compare("#00.0##E0: 99999999.0", df.format(99999999.0), "100E6"); - - df = new DecimalFormat("#.0E0", dfs); - compare("#.0E0: -0.0", df.format(-0.0), "-.0E0"); - compare("#.0E0: 0.0", df.format(0.0), ".0E0"); - compare("#.0E0: 1.0", df.format(1.0), ".1E1"); - compare("#.0E0: 12.0", df.format(12.0), ".12E2"); - compare("#.0E0: 123.0", df.format(123.0), ".12E3"); - compare("#.0E0: 1234.0", df.format(1234.0), ".12E4"); - compare("#.0E0: 9999.0", df.format(9999.0), ".1E5"); - - df = new DecimalFormat("0.#E0", dfs); - compare("0.#E0: -0.0", df.format(-0.0), "-0E0"); - compare("0.#E0: 0.0", df.format(0.0), "0E0"); - compare("0.#E0: 1.0", df.format(1.0), "1E0"); - compare("0.#E0: 12.0", df.format(12.0), "1.2E1"); - compare("0.#E0: 123.0", df.format(123.0), "1.2E2"); - compare("0.#E0: 1234.0", df.format(1234.0), "1.2E3"); - compare("0.#E0: 9999.0", df.format(9999.0), "1E4"); - - df = new DecimalFormat(".0E0", dfs); - compare(".0E0: -0.0", df.format(-0.0), "-.0E0"); - compare(".0E0: 0.0", df.format(0.0), ".0E0"); - compare(".0E0: 1.0", df.format(1.0), ".1E1"); - compare(".0E0: 12.0", df.format(12.0), ".1E2"); - compare(".0E0: 123.0", df.format(123.0), ".1E3"); - compare(".0E0: 1234.0", df.format(1234.0), ".1E4"); - compare(".0E0: 9999.0", df.format(9999.0), ".1E5"); - - df = new DecimalFormat("0.E0", dfs); - // Fails in JDK 1.2.2 - if (!compare(failCount, df.format(0.0), "0.E0")) - failures.set(failCount); - failCount++; - if (!compare(failCount, df.format(1.0), "1.E0")) - failures.set(failCount); - failCount++; - if (!compare(failCount, df.format(12.0), "1.E1")) - failures.set(failCount); - failCount++; - if (!compare(failCount, df.format(123.0), "1.E2")) - failures.set(failCount); - failCount++; - if (!compare(failCount, df.format(1234.0), "1.E3")) - failures.set(failCount); - failCount++; - if (!compare(failCount, df.format(9999.0), "1.E4")) - failures.set(failCount); - failCount++; - - df = new DecimalFormat("##0.00#E0", dfs); - compare("##0.00#E0: 0.1", df.format(0.1), "100E-3"); - compare("##0.00#E0: 0.1234567", df.format(0.1234567), "123.457E-3"); - compare("##0.00#E0: 0.9999999", df.format(0.9999999), "1.00E0"); - compare("##0.00#E0: 0.01", df.format(0.01), "10.0E-3"); - compare("##0.00#E0: 0.01234567", df.format(0.01234567), "12.3457E-3"); - compare("##0.00#E0: 0.09999999", df.format(0.09999999), "100E-3"); - compare("##0.00#E0: 0.001", df.format(0.001), "1.00E-3"); - compare("##0.00#E0: 0.001234567", df.format(0.001234567), "1.23457E-3"); - compare("##0.00#E0: 0.009999999", df.format(0.009999999), "10.0E-3"); - compare("##0.00#E0: 0.0001", df.format(0.0001), "100E-6"); - compare("##0.00#E0: 0.0001234567", df.format(0.0001234567), - "123.457E-6"); - compare("##0.00#E0: 0.0009999999", df.format(0.0009999999), "1.00E-3"); - - df = new DecimalFormat("###0.00#E0", dfs); - compare("###0.00#E0: 0.1", df.format(0.1), "1000E-4"); - compare("###0.00#E0: 0.12345678", df.format(0.12345678), "1234.568E-4"); - compare("###0.00#E0: 0.99999999", df.format(0.99999999), "1.00E0"); - compare("###0.00#E0: 0.01", df.format(0.01), "100E-4"); - compare("###0.00#E0: 0.012345678", df.format(0.012345678), - "123.4568E-4"); - compare("###0.00#E0: 0.099999999", df.format(0.099999999), "1000E-4"); - compare("###0.00#E0: 0.001", df.format(0.001), "10.0E-4"); - compare("###0.00#E0: 0.0012345678", df.format(0.0012345678), - "12.34568E-4"); - compare("###0.00#E0: 0.0099999999", df.format(0.0099999999), "100E-4"); - compare("###0.00#E0: 0.0001", df.format(0.0001), "1.00E-4"); - compare("###0.00#E0: 0.00012345678", df.format(0.00012345678), - "1.234568E-4"); - compare("###0.00#E0: 0.00099999999", df.format(0.00099999999), - "10.0E-4"); - // Fails in JDK 1.2.2 - if (!compare(failCount, df.format(0.00001), "1000E-8")) - failures.set(failCount); - failCount++; - compare("###0.00#E0: 0.000012345678", df.format(0.000012345678), - "1234.568E-8"); - compare("###0.00#E0: 0.000099999999", df.format(0.000099999999), - "1.00E-4"); - - df = new DecimalFormat("###0.0#E0", dfs); - compare("###0.0#E0: 0.1", df.format(0.1), "1000E-4"); - compare("###0.0#E0: 0.1234567", df.format(0.1234567), "1234.57E-4"); - compare("###0.0#E0: 0.9999999", df.format(0.9999999), "1.0E0"); - // Fails in JDK 1.2.2 - if (!compare(failCount, df.format(0.01), "100E-4")) - failures.set(failCount); - failCount++; - compare("###0.0#E0: 0.01234567", df.format(0.01234567), "123.457E-4"); - compare("###0.0#E0: 0.09999999", df.format(0.09999999), "1000E-4"); - compare("###0.0#E0: 0.001", df.format(0.001), "10E-4"); - compare("###0.0#E0: 0.001234567", df.format(0.001234567), "12.3457E-4"); - // Fails in JDK 1.2.2 - if (!compare(failCount, df.format(0.009999999), "100E-4")) - failures.set(failCount); - failCount++; - compare("###0.0#E0: 0.0001", df.format(0.0001), "1.0E-4"); - compare("###0.0#E0: 0.0001234567", df.format(0.0001234567), - "1.23457E-4"); - compare("###0.0#E0: 0.0009999999", df.format(0.0009999999), "10E-4"); - // Fails in JDK 1.2.2 - if (!compare(failCount, df.format(0.00001), "1000E-8")) - failures.set(failCount); - failCount++; - compare("###0.0#E0: 0.00001234567", df.format(0.00001234567), - "1234.57E-8"); - compare("###0.0#E0: 0.00009999999", df.format(0.00009999999), "1.0E-4"); - - assertTrue("Failed " + failures + " of " + failCount, - failures.length() == 0); - - String formatString = "##0.#"; - df = new DecimalFormat(formatString, dfs); - df.setMinimumFractionDigits(30); - compare(formatString + ": 0.000000000000000000000000000000", df - .format(0.0), "0.000000000000000000000000000000"); - compare(formatString + ": -0.000000000000000000000000000000", df - .format(-0.0), "-0.000000000000000000000000000000"); - compare(formatString + ": 1.000000000000000000000000000000", df - .format(1.0), "1.000000000000000000000000000000"); - compare(formatString + ": -1.000000000000000000000000000000", df - .format(-1.0), "-1.000000000000000000000000000000"); - - df = new DecimalFormat(formatString); - df.setMaximumFractionDigits(30); - compare(formatString + ": 0", df.format(0.0), "0"); - compare(formatString + ": -0", df.format(-0.0), "-0"); - compare(formatString + ": 1", df.format(1.0), "1"); - compare(formatString + ": -1", df.format(-1.0), "-1"); - } - - public void test_formatD() { - DecimalFormat format = (DecimalFormat) NumberFormat - .getInstance(Locale.ENGLISH); - format.setGroupingUsed(false); - format.setMaximumFractionDigits(400); - assertEquals("123456789012345", format.format(123456789012345.)); - assertEquals("1", "12345678901234.5", format.format(12345678901234.5)); - assertEquals("2", "1234567890123.25", format.format(1234567890123.25)); - assertEquals("3", "999999999999.375", format.format(999999999999.375)); - assertEquals("4", "99999999999.0625", format.format(99999999999.0625)); - assertEquals("5", "9999999999.03125", format.format(9999999999.03125)); - assertEquals("6", "999999999.015625", format.format(999999999.015625)); - assertEquals("7", "99999999.0078125", format.format(99999999.0078125)); - assertEquals("8", "9999999.00390625", format.format(9999999.00390625)); - assertEquals("9", "999999.001953125", format.format(999999.001953125)); - assertEquals("10", "9999.00048828125", format.format(9999.00048828125)); - assertEquals("11", "999.000244140625", format.format(999.000244140625)); - assertEquals("12", "99.0001220703125", format.format(99.0001220703125)); - assertEquals("13", "9.00006103515625", format.format(9.00006103515625)); - assertEquals("14", "0.000030517578125", format.format(0.000030517578125)); - } - - - public void test_getNegativePrefix() { - DecimalFormat df = new DecimalFormat(); - try { - df.setNegativePrefix("--"); - assertTrue("Incorrect negative prefix", df.getNegativePrefix() - .equals("--")); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - public void test_getNegativeSuffix() { - DecimalFormat df = new DecimalFormat(); - try { - df.setNegativeSuffix("&"); - assertTrue("Incorrect negative suffix", df.getNegativeSuffix() - .equals("&")); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - public void test_getPositivePrefix() { - DecimalFormat df = new DecimalFormat(); - try { - df.setPositivePrefix("++"); - assertTrue("Incorrect positive prefix", df.getPositivePrefix() - .equals("++")); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - public void test_getPositiveSuffix() { - DecimalFormat df = new DecimalFormat(); - try { - df.setPositiveSuffix("%"); - assertTrue("Incorrect positive prefix", df.getPositiveSuffix() - .equals("%")); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - public void test_hashCode() { - try { - DecimalFormat df1 = new DecimalFormat(); - DecimalFormat df2 = (DecimalFormat) df1.clone(); - assertTrue("Hash codes of equals object are not equal", df2 - .hashCode() == df1.hashCode()); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - public void test_parseLjava_lang_StringLjava_text_ParsePosition() { - DecimalFormat format = (DecimalFormat) NumberFormat - .getNumberInstance(Locale.ENGLISH); - ParsePosition pos = new ParsePosition(0); - Number result = format.parse("9223372036854775807", pos); - assertTrue("Wrong result type for Long.MAX_VALUE", - result.getClass() == Long.class); - assertEquals("Wrong result Long.MAX_VALUE", - Long.MAX_VALUE, result.longValue()); - pos = new ParsePosition(0); - result = format.parse("-9223372036854775808", pos); - assertTrue("Wrong result type for Long.MIN_VALUE", - result.getClass() == Long.class); - assertTrue("Wrong result Long.MIN_VALUE: " + result.longValue(), result - .longValue() == Long.MIN_VALUE); - pos = new ParsePosition(0); - result = format.parse("9223372036854775808", pos); - assertTrue("Wrong result type for Long.MAX_VALUE+1", - result.getClass() == Double.class); - assertEquals("Wrong result Long.MAX_VALUE + 1", - (double) Long.MAX_VALUE + 1, result.doubleValue()); - pos = new ParsePosition(0); - result = format.parse("-9223372036854775809", pos); - assertTrue("Wrong result type for Long.MIN_VALUE - 1", - result.getClass() == Double.class); - assertEquals("Wrong result Long.MIN_VALUE - 1", - (double) Long.MIN_VALUE - 1, result.doubleValue()); - - pos = new ParsePosition(0); - result = format.parse("18446744073709551629", pos); - assertTrue("Wrong result type for overflow", - result.getClass() == Double.class); - assertEquals("Wrong result for overflow", - 18446744073709551629d, result.doubleValue()); - - pos = new ParsePosition(0); - result = format.parse("42325917317067571199", pos); - assertTrue("Wrong result type for overflow a: " + result, result - .getClass() == Double.class); - assertTrue("Wrong result for overflow a: " + result, result - .doubleValue() == 42325917317067571199d); - pos = new ParsePosition(0); - result = format.parse("4232591731706757119E1", pos); - assertTrue("Wrong result type for overflow b: " + result, result - .getClass() == Double.class); - assertEquals("Wrong result for overflow b: " + result, - 42325917317067571190d, result.doubleValue()); - pos = new ParsePosition(0); - result = format.parse(".42325917317067571199E20", pos); - assertTrue("Wrong result type for overflow c: " + result, result - .getClass() == Double.class); - assertTrue("Wrong result for overflow c: " + result, result - .doubleValue() == 42325917317067571199d); - pos = new ParsePosition(0); - result = format.parse("922337203685477580.9E1", pos); - assertTrue("Wrong result type for overflow d: " + result, result - .getClass() == Double.class); - assertTrue("Wrong result for overflow d: " + result, result - .doubleValue() == 9223372036854775809d); - pos = new ParsePosition(0); - result = format.parse("9.223372036854775809E18", pos); - assertTrue("Wrong result type for overflow e: " + result, result - .getClass() == Double.class); - assertTrue("Wrong result for overflow e: " + result, result - .doubleValue() == 9223372036854775809d); - - // test parse with multipliers - format.setMultiplier(100); - result = format.parse("9223372036854775807", new ParsePosition(0)); - assertEquals("Wrong result type multiplier 100: " + result, Long.class, result.getClass()); - // RI on windows and linux both answer with a slightly rounded result - assertTrue("Wrong result for multiplier 100: " + result, result - .longValue() == 92233720368547760L); - format.setMultiplier(1000); - result = format.parse("9223372036854775807", new ParsePosition(0)); - assertTrue("Wrong result type multiplier 1000: " + result, result - .getClass() == Long.class); - assertTrue("Wrong result for multiplier 1000: " + result, result - .longValue() == 9223372036854776L); - - format.setMultiplier(10000); - result = format.parse("9223372036854775807", new ParsePosition(0)); - assertTrue("Wrong result type multiplier 10000: " + result, result - .getClass() == Double.class); - assertTrue("Wrong result for multiplier 10000: " + result, result - .doubleValue() == 922337203685477.5807d); - - } -} diff --git a/luni/src/test/java/libcore/java/text/OldFieldPositionTest.java b/luni/src/test/java/libcore/java/text/OldFieldPositionTest.java deleted file mode 100644 index b6fbd98..0000000 --- a/luni/src/test/java/libcore/java/text/OldFieldPositionTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.text; - -import java.text.DateFormat; -import java.text.FieldPosition; - -public class OldFieldPositionTest extends junit.framework.TestCase { - - public void test_hashCode() { - // Test for method int java.text.FieldPosition.hashCode() - FieldPosition fpos1 = new FieldPosition(1); - FieldPosition fpos2 = new FieldPosition(1); - assertTrue("test 1: hash codes are not equal for equal objects.", - fpos1.hashCode() == fpos2.hashCode()); - fpos1.setBeginIndex(5); - fpos1.setEndIndex(110); - assertTrue("test 2: hash codes are equal for non equal objects.", - fpos1.hashCode() != fpos2.hashCode()); - fpos2.setBeginIndex(5); - fpos2.setEndIndex(110); - assertTrue("test 3: hash codes are not equal for equal objects.", - fpos1.hashCode() == fpos2.hashCode()); - - FieldPosition fpos3 = new FieldPosition( - DateFormat.Field.DAY_OF_WEEK_IN_MONTH); - - assertTrue("test 4: hash codes are equal for non equal objects.", - fpos2.hashCode() != fpos3.hashCode()); - } - - public void test_setBeginIndexI() { - // Test for method void java.text.FieldPosition.setBeginIndex(int) - FieldPosition fpos = new FieldPosition(1); - fpos.setBeginIndex(2); - fpos.setEndIndex(3); - assertEquals("beginIndex should have been set to 2", 2, fpos - .getBeginIndex()); - - fpos.setBeginIndex(Integer.MAX_VALUE); - assertEquals("beginIndex should have been set to Integer.MAX_VALUE", - Integer.MAX_VALUE, fpos.getBeginIndex()); - - fpos.setBeginIndex(-1); - assertEquals("beginIndex should have been set to -1", - -1, fpos.getBeginIndex()); - } - - public void test_setEndIndexI() { - // Test for method void java.text.FieldPosition.setEndIndex(int) - FieldPosition fpos = new FieldPosition(1); - fpos.setEndIndex(3); - fpos.setBeginIndex(2); - assertEquals("EndIndex should have been set to 3", 3, fpos - .getEndIndex()); - - fpos.setEndIndex(Integer.MAX_VALUE); - assertEquals("endIndex should have been set to Integer.MAX_VALUE", - Integer.MAX_VALUE, fpos.getEndIndex()); - - fpos.setEndIndex(-1); - assertEquals("endIndex should have been set to -1", - -1, fpos.getEndIndex()); - } -} diff --git a/luni/src/test/java/libcore/java/text/OldMessageFormatTest.java b/luni/src/test/java/libcore/java/text/OldMessageFormatTest.java deleted file mode 100644 index 2701d0e..0000000 --- a/luni/src/test/java/libcore/java/text/OldMessageFormatTest.java +++ /dev/null @@ -1,463 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.text; - -import java.text.ChoiceFormat; -import java.text.DateFormat; -import java.text.FieldPosition; -import java.text.Format; -import java.text.MessageFormat; -import java.text.NumberFormat; -import java.text.ParseException; -import java.text.ParsePosition; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; -import java.util.TimeZone; -import junit.framework.TestCase; -import tests.support.Support_MessageFormat; - -public class OldMessageFormatTest extends TestCase { - - private MessageFormat format1; - - protected void setUp() { - Locale.setDefault(Locale.US); - - // test with repeating formats and max argument index < max offset - String pattern = "A {3, number, currency} B {2, time} C {0, number, percent} D {4} E {1,choice,0#off|1#on} F {0, date}"; - format1 = new MessageFormat(pattern); - } - - public void test_applyPatternLjava_lang_String_AndroidFailure() { - MessageFormat format = new MessageFormat("test"); - format.setLocale(Locale.FRENCH); // use French since English has the - // same LONG and FULL time patterns - format.applyPattern("{0,time, Full}"); - assertEquals("Wrong full time pattern", "{0,time,full}", format - .toPattern()); - } - - public void test_formatToCharacterIteratorLjava_lang_Object() { - // Test for method formatToCharacterIterator(java.lang.Object) - new Support_MessageFormat( - "test_formatToCharacterIteratorLjava_lang_Object") - .t_formatToCharacterIterator(); - - try { - new MessageFormat("{1, number}").formatToCharacterIterator(null); - fail("NullPointerException was not thrown."); - } catch(NullPointerException npe) { - //expected - } - - try { - new MessageFormat("{0, time}").formatToCharacterIterator(new Object[]{""}); - fail("IllegalArgumentException was not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - } - - public void test_getLocale() { - try { - Locale[] l = { - Locale.FRANCE, - Locale.KOREA, - new Locale(Locale.FRANCE.getCountry(), Locale.FRANCE - .getLanguage()), new Locale("mk"), - new Locale("mk", "MK"), Locale.US, - new Locale("#ru", "@31230") }; - - String pattern = "getLocale test {0,number,#,####}"; - MessageFormat mf; - - for (int i = 0; i < 0; i++) { - mf = new MessageFormat(pattern, l[i]); - Locale result = mf.getLocale(); - assertEquals("Returned local: " + result + " instead of " - + l[i], l[i], result); - assertEquals("Returned language: " + result.getLanguage() - + " instead of " + l[i].getLanguage(), l[i] - .getLanguage(), result.getLanguage()); - assertEquals("Returned country: " + result.getCountry() - + " instead of " + l[i].getCountry(), - l[i].getCountry(), result.getCountry()); - } - - mf = new MessageFormat(pattern); - mf.setLocale(null); - Locale result = mf.getLocale(); - assertEquals("Returned local: " + result + " instead of null", - null, result); - } catch (Exception e) { - fail("unexpected exception " + e.toString()); - } - } - - /** - * java.text.MessageFormat#setFormat(int, Format) Test of method - * java.text.MessageFormat#setFormat(int, Format). Case 1: Compare - * getFormats() results after calls to setFormat(). Case 2: Try to - * call setFormat() using incorrect index. - */ - public void test_setFormatILjava_text_Format() { - try { - // case 1: Compare getFormats() results after calls to setFormat() - MessageFormat f1 = (MessageFormat) format1.clone(); - f1.setFormat(0, DateFormat.getTimeInstance()); - f1.setFormat(1, DateFormat.getTimeInstance()); - f1.setFormat(2, NumberFormat.getInstance()); - f1.setFormat(3, new ChoiceFormat("0#off|1#on")); - f1.setFormat(4, new ChoiceFormat("1#few|2#ok|3#a lot")); - f1.setFormat(5, DateFormat.getTimeInstance()); - - Format[] formats = f1.getFormats(); - formats = f1.getFormats(); - - Format[] correctFormats = new Format[] { - DateFormat.getTimeInstance(), DateFormat.getTimeInstance(), - NumberFormat.getInstance(), new ChoiceFormat("0#off|1#on"), - new ChoiceFormat("1#few|2#ok|3#a lot"), - DateFormat.getTimeInstance() }; - - assertEquals("Test1A:Returned wrong number of formats:", - correctFormats.length, formats.length); - for (int i = 0; i < correctFormats.length; i++) { - assertEquals( - "Test1B:wrong format for pattern index " + i + ":", - correctFormats[i], formats[i]); - } - - // case 2: Try to setFormat using incorrect index - try { - f1.setFormat(-1, DateFormat.getDateInstance()); - fail("Expected ArrayIndexOutOfBoundsException was not thrown"); - f1.setFormat(f1.getFormats().length, DateFormat - .getDateInstance()); - fail("Expected ArrayIndexOutOfBoundsException was not thrown"); - } catch (ArrayIndexOutOfBoundsException e) { - // expected - } - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - public void test_format$Ljava_lang_ObjectLjava_lang_StringBufferLjava_text_FieldPosition() { - // Test for method java.lang.StringBuffer - // java.text.MessageFormat.format(java.lang.Object [], - // java.lang.StringBuffer, java.text.FieldPosition) - MessageFormat format = new MessageFormat("{1,number,integer}"); - StringBuffer buffer = new StringBuffer(); - format.format(new Object[] { "0", new Double(53.863) }, buffer, - new FieldPosition(MessageFormat.Field.ARGUMENT)); - assertEquals("Wrong result", "54", buffer.toString()); - - format.format(new Object[] { "0", new Double(53.863) }, buffer, - new FieldPosition(MessageFormat.Field.ARGUMENT)); - - assertEquals("Wrong result", "5454", buffer.toString()); - - buffer = new StringBuffer(); - format - .applyPattern("{0,choice,0#zero|1#one '{1,choice,2#two {2,time}}'}"); - Date date = new Date(); - String expected = "one two " - + DateFormat.getTimeInstance().format(date); - format.format(new Object[] { new Double(1.6), - new Integer(3), date }, buffer, new FieldPosition(MessageFormat - .Field.ARGUMENT)); - assertEquals("Choice not recursive:\n" + expected + "\n" + buffer, - expected, buffer.toString()); - - StringBuffer str = format.format(new Object[] { new Double(0.6), - new Integer(3)}, buffer, null); - - assertEquals(expected + "zero", str.toString()); - assertEquals(expected + "zero", buffer.toString()); - - try { - format.format(new Object[] { "0", new Double(1), "" }, buffer, - new FieldPosition(MessageFormat.Field.ARGUMENT)); - fail("IllegalArgumentException was not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - - try { - format.format(new Object[] { "", new Integer(3)}, buffer, - new FieldPosition(MessageFormat.Field.ARGUMENT)); - fail("IllegalArgumentException was not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - } - - public void test_formatLjava_lang_StringLjava_lang_Object() { - TimeZone.setDefault(TimeZone.getTimeZone("UTC")); - int iCurrency = 123; - int iInteger = Integer.MIN_VALUE; - - Date date = new Date(12345678); - Object[] args = { date, iCurrency, iInteger }; - String resStr = "Date: Jan 1, 1970 Currency: $" + iCurrency - + ".00 Integer: -2,147,483,648"; - String pattern = "Date: {0,date} Currency: {1, number, currency} Integer: {2, number, integer}"; - String sFormat = MessageFormat.format(pattern, (Object[]) args); - assertEquals( - "format(String, Object[]) with valid parameters returns incorrect string: case 1", - sFormat, resStr); - - pattern = "abc {4, number, integer} def {3,date} ghi {2,number} jkl {1,choice,0#low|1#high} mnop {0}"; - resStr = "abc -2,147,483,648 def Jan 1, 1970 ghi -2,147,483,648 jkl high mnop -2,147,483,648"; - Object[] args_ = { iInteger, 1, iInteger, date, iInteger }; - sFormat = MessageFormat.format(pattern, args_); - assertEquals( - "format(String, Object[]) with valid parameters returns incorrect string: case 1", - sFormat, resStr); - - try { - args = null; - MessageFormat.format(null, args); - fail("Doesn't throw IllegalArgumentException: null, null"); - } catch (Exception e) { - // expected - } - - try { - MessageFormat.format("Invalid {1,foobar} format descriptor!", - new Object[] {iInteger} ); - fail("Doesn't throw IllegalArgumentException with invalid pattern as a parameter: case 1"); - } catch (IllegalArgumentException ex) { - // expected - } - - try { - MessageFormat.format( - "Invalid {1,date,invalid-spec} format descriptor!", new Object[]{""}); - fail("Doesn't throw IllegalArgumentException with invalid pattern as a parameter: case 2"); - } catch (IllegalArgumentException ex) { - // expected - } - - try { - MessageFormat.format("{0,number,integer", new Object[] {iInteger}); - fail("Doesn't throw IllegalArgumentException, doesn't detect unmatched brackets"); - } catch (IllegalArgumentException ex) { - // expected - } - - try { - MessageFormat.format( - "Valid {1, date} format {0, number} descriptor!", new Object[]{ "" } ); - fail("Doesn't throw IllegalArgumentException with invalid Object array"); - } catch (IllegalArgumentException ex) { - // expected - } - } - - public void test_formatLjava_lang_ObjectLjava_lang_StringBufferLjava_text_FieldPosition() { - // Test for method java.lang.StringBuffer - // java.text.MessageFormat.format(java.lang.Object, - // java.lang.StringBuffer, java.text.FieldPosition) - new Support_MessageFormat( - "test_formatLjava_lang_ObjectLjava_lang_StringBufferLjava_text_FieldPosition") - .t_format_with_FieldPosition(); - - String pattern = "On {4,date} at {3,time}, he ate {2,number, integer} " + - "hamburger{2,choice,1#|1<s}."; - MessageFormat format = new MessageFormat(pattern, Locale.US); - - Object[] objects = new Object[] { "", new Integer(3), 8, ""}; - - try { - format.format(objects, new StringBuffer(), - new FieldPosition(DateFormat.Field.AM_PM)); - fail("IllegalArgumentException was not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - } - - public void test_setFormats$Ljava_text_Format() { - try { - MessageFormat f1 = (MessageFormat) format1.clone(); - - // case 1: Test with repeating formats and max argument index < max - // offset - // compare getFormats() results after calls to setFormats(Format[]) - Format[] correctFormats = new Format[] { - DateFormat.getTimeInstance(), - new ChoiceFormat("0#off|1#on"), - DateFormat.getTimeInstance(), - NumberFormat.getCurrencyInstance(), - new ChoiceFormat("1#few|2#ok|3#a lot") }; - - f1.setFormats(correctFormats); - Format[] formats = f1.getFormats(); - - assertTrue("Test1A:Returned wrong number of formats:", - correctFormats.length <= formats.length); - for (int i = 0; i < correctFormats.length; i++) { - assertEquals("Test1B:wrong format for argument index " + i - + ":", correctFormats[i], formats[i]); - } - - // case 2: Try to pass null argument to setFormats(). - try { - f1.setFormats(null); - fail("Expected exception NullPointerException was not thrown"); - } catch (NullPointerException e) { - // expected - } - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - public void test_parseLjava_lang_String() throws ParseException { - String pattern = "A {3, number, currency} B {2, time} C {0, number, percent} D {4} E {1,choice,0#off|1#on} F {0, date}"; - MessageFormat mf = new MessageFormat(pattern); - String sToParse = "A $12,345.00 B 9:56:07 AM C 3,200% D 1/15/70 9:56 AM E on F Jan 1, 1970"; - Object[] result; - try { - result = mf.parse(sToParse); - - assertTrue("No result: " + result.length, result.length == 5); - assertTrue("Object 0 is not date", result[0] instanceof Date); - assertEquals("Object 1 is not stringr", result[1].toString(), "1.0"); - assertTrue("Object 2 is not date", result[2] instanceof Date); - assertEquals("Object 3 is not number", result[3].toString(), - "12345"); - assertEquals("Object 4 is not string", result[4].toString(), - "1/15/70 9:56 AM"); - - } catch (java.text.ParseException pe) { - fail("ParseException is thrown for incorrect string " + sToParse); - } - - sToParse = "xxdate is Feb 28, 1999"; - try { - result = format1.parse(sToParse); - fail("ParseException is thrown for incorrect string " + sToParse); - } catch (java.text.ParseException pe) { - // expected - } - - sToParse = "vm=Test, @3 4 6, 3 "; - mf = new MessageFormat("vm={0},{1},{2}"); - try { - result = mf.parse(sToParse); - assertTrue("No result: " + result.length, result.length == 3); - assertEquals("Object 0 is not string", result[0].toString(), "Test"); - assertEquals("Object 1 is not string", result[1].toString(), - " @3 4 6"); - assertEquals("Object 2 is not string", result[2].toString(), - " 3 "); - } catch (java.text.ParseException pe) { - fail("ParseException is thrown for correct string " + sToParse); - } - - try { - result = mf.parse(null); - fail("ParseException is not thrown for null " + sToParse); - } catch (java.text.ParseException pe) { - // expected - } - } - - /** - * java.text.MessageFormat#parseObject(java.lang.String, - * java.text.ParsePosition) Test of method - * java.text.MessageFormat#parseObject(java.lang.String, - * java.text.ParsePosition). Case 1: Parsing of correct data string. - * Case 2: Parsing of partial correct data string. Case 3: Try to use - * argument ParsePosition as null. - */ - public void test_parseObjectLjava_lang_StringLjavajava_text_ParsePosition() { - MessageFormat mf = new MessageFormat("{0,number,#.##}, {0,number,#.#}"); - try { - // case 1: Try to parse correct data string. - Object[] objs = { new Double(3.1415) }; - String result = mf.format(objs); - // result now equals "3.14, 3.1" - Object[] res = null; - ParsePosition pp = new ParsePosition(0); - int parseIndex = pp.getIndex(); - res = (Object[]) mf.parseObject(result, pp); - assertTrue("Parse operation return null", res != null); - assertTrue("parse operation return array with incorrect length", - 1 == res.length); - assertTrue("ParseIndex is incorrect", pp.getIndex() != parseIndex); - assertTrue("Result object is incorrect", new Double(3.1) - .equals(res[0])); - - // case 2: Try to parse partially correct data string. - pp.setIndex(0); - char[] cur = result.toCharArray(); - cur[cur.length / 2] = 'Z'; - String partialCorrect = new String(cur); - res = (Object[]) mf.parseObject(partialCorrect, pp); - assertTrue("Parse operation return null", res == null); - assertTrue("ParseIndex is incorrect", pp.getIndex() == 0); - assertTrue("ParseErrorIndex is incorrect", - pp.getErrorIndex() == cur.length / 2); - - // case 3: Try to use argument ParsePosition as null. - try { - mf.parseObject(result, null); - fail("Expected NullPointerException was not thrown"); - } catch (NullPointerException e) { - // expected - } - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - public void test_format_Object() { - // Regression for HARMONY-1875 - Locale.setDefault(Locale.CANADA); - TimeZone.setDefault(TimeZone.getTimeZone("UTC")); - String pat = "text here {0,date,yyyyyyyyy} and here"; - Calendar c = Calendar.getInstance(); - String etalon = "text here 00000" + c.get(Calendar.YEAR) + " and here"; - MessageFormat obj = new MessageFormat(pat); - assertEquals(etalon, obj.format(new Object[] { new Date() })); - } - - public void test_parseLjava_lang_StringLjava_text_ParsePosition() { - ParsePosition pos = new ParsePosition(2); - - MessageFormat mf = new MessageFormat("{0}; {0}; {0}"); - String parse = "a; b; c"; - try { - mf.parse(parse, null); - fail("NullPointerException was not thrown."); - } catch(NullPointerException npe) { - //expected - } - - try { - mf.parse(null, pos); - } catch(NullPointerException npe) { - fail("NullPointerException was thrown."); - } - } -} diff --git a/luni/src/test/java/libcore/java/text/OldNumberFormatTest.java b/luni/src/test/java/libcore/java/text/OldNumberFormatTest.java index b7ae098..d281a91 100644 --- a/luni/src/test/java/libcore/java/text/OldNumberFormatTest.java +++ b/luni/src/test/java/libcore/java/text/OldNumberFormatTest.java @@ -16,7 +16,6 @@ */ package libcore.java.text; -import dalvik.annotation.BrokenTest; import java.text.ChoiceFormat; import java.text.DecimalFormat; import java.text.FieldPosition; @@ -50,10 +49,14 @@ public class OldNumberFormatTest extends TestCase { Locale arLocale = new Locale("ar", "AE"); format = (DecimalFormat) NumberFormat.getIntegerInstance(arLocale); - assertEquals("#0;#0-", format.toPattern()); - assertEquals("\u0666-", format.format(-6)); - assertEquals(new Long(-36), format.parse("36-")); - assertEquals(new Long(-36), format.parseObject("36-")); + assertEquals("#,##0", format.toPattern()); + assertEquals("\u0666\u0667", format.format(67)); + + assertEquals("\u200f-\u0666", format.format(-6)); + assertEquals(-36L, format.parse("-36")); + + // New Arabic formats do not support '-' to right of digits. + assertEquals(36L, format.parseObject("36-")); assertEquals(0, format.getMaximumFractionDigits()); assertTrue(format.isParseIntegerOnly()); } @@ -729,7 +732,7 @@ public class OldNumberFormatTest extends TestCase { + " instead of Integer.MIN_VALUE", result == 0); } - @BrokenTest("Fails in CTS, passes in CoreTestRunner") + // Broken Test: Fails in CTS, passes in CoreTestRunner public void test_parseLjava_lang_String() { NumberFormat nf1 = NumberFormat.getInstance(); try { diff --git a/luni/src/test/java/libcore/java/text/OldSimpleDateFormatTest.java b/luni/src/test/java/libcore/java/text/OldSimpleDateFormatTest.java deleted file mode 100644 index 1cc7554..0000000 --- a/luni/src/test/java/libcore/java/text/OldSimpleDateFormatTest.java +++ /dev/null @@ -1,539 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.text; - -import java.text.DateFormat; -import java.text.DateFormatSymbols; -import java.text.FieldPosition; -import java.text.ParsePosition; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.Locale; -import java.util.SimpleTimeZone; -import java.util.TimeZone; - -public class OldSimpleDateFormatTest extends junit.framework.TestCase { - - SimpleDateFormat format = null; - SimpleDateFormat pFormat = null; - - @Override - protected void setUp() throws Exception { - TimeZone.setDefault(TimeZone.getTimeZone("GMT")); - format = new SimpleDateFormat("", Locale.ENGLISH); - pFormat = new SimpleDateFormat("", Locale.ENGLISH); - } - - @Override - protected void tearDown() throws Exception { - format = null; - pFormat = null; - } - - class FormatTester { - boolean testsFailed = false; - - public void test(String pattern, Calendar cal, String expected, int field) { - StringBuffer buffer = new StringBuffer(); - FieldPosition position = new FieldPosition(field); - format.applyPattern(pattern); - format.format(cal.getTime(), buffer, position); - String result = buffer.toString(); - if (!result.equals(expected)) { - System.out.println("Wrong format: \"" + pattern - + "\" expected: " + expected + " result: " - + result); - testsFailed = true; - } - } - - public void parse(String pattern, String input, Date expected, int start, int end) { - pFormat.applyPattern(pattern); - ParsePosition position = new ParsePosition(start); - Date result = pFormat.parse(input, position); - assertTrue("Wrong result: " + pattern + " input: " + input - + " expected: " + expected + " result: " + result, expected - .equals(result)); - assertTrue("Wrong end position: " + pattern + " input: " + input, - position.getIndex() == end); - } - - public void verifyFormatTimezone(String timeZoneId, String expected1, - String expected2, Date date) { - format.setTimeZone(SimpleTimeZone.getTimeZone(timeZoneId)); - format.applyPattern("z, zzzz"); - assertEquals("Test z for TimeZone : " + timeZoneId, expected1, - format.format(date)); - - format.applyPattern("Z, ZZZZ"); - assertEquals("Test Z for TimeZone : " + timeZoneId, expected2, - format.format(date)); - } - } - - /** - * java.text.SimpleDateFormat#SimpleDateFormat(java.lang.String, - * java.text.DateFormatSymbols) - */ - public void test_ConstructorLjava_lang_StringLjava_text_DateFormatSymbols() { - // Test for method java.text.SimpleDateFormat(java.lang.String, - // java.text.DateFormatSymbols) - DateFormatSymbols symbols = new DateFormatSymbols(Locale.ENGLISH); - symbols.setEras(new String[] { "Before", "After" }); - SimpleDateFormat f2 = new SimpleDateFormat("y'y'yy", symbols); - assertTrue("Wrong class", f2.getClass() == SimpleDateFormat.class); - assertEquals("Wrong pattern", "y'y'yy", f2.toPattern()); - assertTrue("Wrong symbols", f2.getDateFormatSymbols().equals(symbols)); - assertTrue("Doesn't work", - f2.format(new Date()).getClass() == String.class); - - try { - new SimpleDateFormat(null, symbols); - fail("NullPointerException was not thrown."); - } catch(NullPointerException npe) { - //expected - } - - try { - new SimpleDateFormat("eee", symbols); - fail("IllegalArgumentException was not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - } - - public void test_ConstructorLjava_lang_StringLjava_util_Locale() { - // Test for method java.text.SimpleDateFormat(java.lang.String, - // java.util.Locale) - SimpleDateFormat f2 = new SimpleDateFormat("'yyyy' MM yy", - Locale.GERMAN); - assertTrue("Wrong class", f2.getClass() == SimpleDateFormat.class); - assertEquals("Wrong pattern", "'yyyy' MM yy", f2.toPattern()); - assertTrue("Wrong symbols", f2.getDateFormatSymbols().equals( - new DateFormatSymbols(Locale.GERMAN))); - assertTrue("Doesn't work", - f2.format(new Date()).getClass() == String.class); - - try { - new SimpleDateFormat(null, Locale.GERMAN); - fail("NullPointerException was not thrown."); - } catch(NullPointerException npe) { - //expected - } - try { - new SimpleDateFormat("eee", Locale.GERMAN); - fail("IllegalArgumentException was not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - } - - public void test_applyLocalizedPatternLjava_lang_String() { - // Test for method void - // java.text.SimpleDateFormat.applyLocalizedPattern(java.lang.String) - SimpleDateFormat f2 = new SimpleDateFormat("y", new Locale("de", "CH")); - // BEGIN android-removed - // This test doesn't work like this. The cause lies inside of icu - // that doesn't support localized pattern characters anymore. So this - // test fails because the pattern template contains characters that are - // not part of the standard pattern returned for every locale. - // The default pattern characters are: GyMdkHmsSEDFwWahKzZ - // - // f2.applyLocalizedPattern("GuMtkHmsSEDFwWahKz"); - // String pattern = f2.toPattern(); - // assertTrue("Wrong pattern: " + pattern, pattern - // .equals("GyMdkHmsSEDFwWahKz")); - // - // test the new "Z" pattern char - // f2 = new SimpleDateFormat("y", new Locale("de", "CH")); - // f2.applyLocalizedPattern("G u M t Z"); - // pattern = f2.toPattern(); - // assertTrue("Wrong pattern: " + pattern, pattern.equals("G y M d Z")); - // END android-removed - - // test invalid patterns - try { - f2.applyLocalizedPattern("b"); - fail("Expected IllegalArgumentException for pattern with invalid pattern letter: b"); - } catch (IllegalArgumentException e) { - } - - try { - // ICU only! this fails on the RI - f2.applyLocalizedPattern("u"); - fail("Expected IllegalArgumentException for pattern with invalid pattern letter: u"); - } catch (IllegalArgumentException e) { - } - - try { - f2.applyLocalizedPattern("a '"); - fail("Expected IllegalArgumentException for pattern with unterminated quote: a '"); - } catch (IllegalArgumentException e) { - } - - try { - f2.applyLocalizedPattern(null); - fail("Expected NullPointerException for null pattern"); - } catch (NullPointerException e) { - } - } - - /** - * java.text.SimpleDateFormat#applyPattern(java.lang.String) - */ - public void test_applyPatternLjava_lang_String() { - // Test for method void - // java.text.SimpleDateFormat.applyPattern(java.lang.String) - SimpleDateFormat f2 = new SimpleDateFormat("y", new Locale("de", "CH")); - // BEGIN android-changed - f2.applyPattern("GyMdkHmsSEDFwWahKzZ"); - assertEquals("Wrong pattern", "GyMdkHmsSEDFwWahKzZ", f2.toPattern()); - // END android-changed - - // test invalid patterns - try { - f2.applyPattern("u"); - fail("Expected IllegalArgumentException for pattern with invalid patter letter: u"); - } catch (IllegalArgumentException e) { - } - } - - public void test_hashCode() { - SimpleDateFormat format = (SimpleDateFormat) DateFormat.getInstance(); - SimpleDateFormat clone = (SimpleDateFormat) format.clone(); - assertTrue("clone has not equal hash code", clone.hashCode() == format - .hashCode()); - format.format(new Date()); - assertTrue("clone has not equal hash code after format", clone - .hashCode() == format.hashCode()); - DateFormatSymbols symbols = new DateFormatSymbols(Locale.ENGLISH); - symbols.setEras(new String[] { "Before", "After" }); - SimpleDateFormat format2 = new SimpleDateFormat("y'y'yy", symbols); - assertFalse("objects has equal hash code", format2.hashCode() == format - .hashCode()); - } - - public void test_formatLjava_util_DateLjava_lang_StringBufferLjava_text_FieldPosition() { - FormatTester test = new FormatTester(); - - Calendar cal = new GregorianCalendar(1999, Calendar.JUNE, 2, 15, 3, 6); - test.test(" G", cal, " AD", DateFormat.ERA_FIELD); - test.test(" GG", cal, " AD", DateFormat.ERA_FIELD); - test.test(" GGG", cal, " AD", DateFormat.ERA_FIELD); - test.test(" G", new GregorianCalendar(-1999, Calendar.JUNE, 2), " BC", - DateFormat.ERA_FIELD); - - test.test(" M", cal, " 6", DateFormat.MONTH_FIELD); - test.test(" M", new GregorianCalendar(1999, Calendar.NOVEMBER, 2), - " 11", DateFormat.MONTH_FIELD); - test.test(" MM", cal, " 06", DateFormat.MONTH_FIELD); - test.test(" MMM", cal, " Jun", DateFormat.MONTH_FIELD); - test.test(" MMMM", cal, " June", DateFormat.MONTH_FIELD); - test.test(" MMMMM", cal, " J", DateFormat.MONTH_FIELD); - - test.test(" d", cal, " 2", DateFormat.DATE_FIELD); - test.test(" d", new GregorianCalendar(1999, Calendar.NOVEMBER, 12), - " 12", DateFormat.DATE_FIELD); - test.test(" dd", cal, " 02", DateFormat.DATE_FIELD); - test.test(" dddd", cal, " 0002", DateFormat.DATE_FIELD); - - test.test(" h", cal, " 3", DateFormat.HOUR1_FIELD); - test.test(" h", new GregorianCalendar(1999, Calendar.NOVEMBER, 12), - " 12", DateFormat.HOUR1_FIELD); - test.test(" hh", cal, " 03", DateFormat.HOUR1_FIELD); - test.test(" hhhh", cal, " 0003", DateFormat.HOUR1_FIELD); - - test.test(" H", cal, " 15", DateFormat.HOUR_OF_DAY0_FIELD); - test.test(" H", - new GregorianCalendar(1999, Calendar.NOVEMBER, 12, 4, 0), " 4", - DateFormat.HOUR_OF_DAY0_FIELD); - test.test(" H", new GregorianCalendar(1999, Calendar.NOVEMBER, 12, 12, - 0), " 12", DateFormat.HOUR_OF_DAY0_FIELD); - test.test(" H", new GregorianCalendar(1999, Calendar.NOVEMBER, 12), - " 0", DateFormat.HOUR_OF_DAY0_FIELD); - test.test(" HH", cal, " 15", DateFormat.HOUR_OF_DAY0_FIELD); - test.test(" HHHH", cal, " 0015", DateFormat.HOUR_OF_DAY0_FIELD); - - test.test(" m", cal, " 3", DateFormat.MINUTE_FIELD); - test.test(" m", new GregorianCalendar(1999, Calendar.NOVEMBER, 12, 4, - 47), " 47", DateFormat.MINUTE_FIELD); - test.test(" mm", cal, " 03", DateFormat.MINUTE_FIELD); - test.test(" mmmm", cal, " 0003", DateFormat.MINUTE_FIELD); - - test.test(" s", cal, " 6", DateFormat.SECOND_FIELD); - test.test(" s", new GregorianCalendar(1999, Calendar.NOVEMBER, 12, 4, - 47, 13), " 13", DateFormat.SECOND_FIELD); - test.test(" ss", cal, " 06", DateFormat.SECOND_FIELD); - test.test(" ssss", cal, " 0006", DateFormat.SECOND_FIELD); - - test.test(" S", cal, " 0", DateFormat.MILLISECOND_FIELD); - Calendar temp = new GregorianCalendar(); - temp.set(Calendar.MILLISECOND, 961); - - test.test(" SS", temp, " 961", DateFormat.MILLISECOND_FIELD); - test.test(" SSSS", cal, " 0000", DateFormat.MILLISECOND_FIELD); - - test.test(" SS", cal, " 00", DateFormat.MILLISECOND_FIELD); - - test.test(" E", cal, " Wed", DateFormat.DAY_OF_WEEK_FIELD); - test.test(" EE", cal, " Wed", DateFormat.DAY_OF_WEEK_FIELD); - test.test(" EEE", cal, " Wed", DateFormat.DAY_OF_WEEK_FIELD); - test.test(" EEEE", cal, " Wednesday", DateFormat.DAY_OF_WEEK_FIELD); - test.test(" EEEEE", cal, " W", DateFormat.DAY_OF_WEEK_FIELD); - - test.test(" D", cal, " 153", DateFormat.DAY_OF_YEAR_FIELD); - test.test(" DD", cal, " 153", DateFormat.DAY_OF_YEAR_FIELD); - test.test(" DDDD", cal, " 0153", DateFormat.DAY_OF_YEAR_FIELD); - - test.test(" F", cal, " 1", DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD); - test.test(" F", new GregorianCalendar(1999, Calendar.NOVEMBER, 14), - " 2", DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD); - test.test(" FF", cal, " 01", DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD); - test.test(" FFFF", cal, " 0001", DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD); - - test.test(" a", cal, " PM", DateFormat.AM_PM_FIELD); - test.test(" a", new GregorianCalendar(1999, Calendar.NOVEMBER, 14), - " AM", DateFormat.AM_PM_FIELD); - test.test(" a", new GregorianCalendar(1999, Calendar.NOVEMBER, 14, 12, - 0), " PM", DateFormat.AM_PM_FIELD); - test.test(" aa", cal, " PM", DateFormat.AM_PM_FIELD); - test.test(" aaa", cal, " PM", DateFormat.AM_PM_FIELD); - test.test(" aaaa", cal, " PM", DateFormat.AM_PM_FIELD); - test.test(" aaaaa", cal, " PM", DateFormat.AM_PM_FIELD); - - test.test(" k", cal, " 15", DateFormat.HOUR_OF_DAY1_FIELD); - test.test(" k", - new GregorianCalendar(1999, Calendar.NOVEMBER, 12, 4, 0), " 4", - DateFormat.HOUR_OF_DAY1_FIELD); - test.test(" k", new GregorianCalendar(1999, Calendar.NOVEMBER, 12, 12, - 0), " 12", DateFormat.HOUR_OF_DAY1_FIELD); - test.test(" k", new GregorianCalendar(1999, Calendar.NOVEMBER, 12), - " 24", DateFormat.HOUR_OF_DAY1_FIELD); - test.test(" kk", cal, " 15", DateFormat.HOUR_OF_DAY1_FIELD); - test.test(" kkkk", cal, " 0015", DateFormat.HOUR_OF_DAY1_FIELD); - - test.test(" K", cal, " 3", DateFormat.HOUR0_FIELD); - test.test(" K", new GregorianCalendar(1999, Calendar.NOVEMBER, 12), - " 0", DateFormat.HOUR0_FIELD); - test.test(" KK", cal, " 03", DateFormat.HOUR0_FIELD); - test.test(" KKKK", cal, " 0003", DateFormat.HOUR0_FIELD); - - format.applyPattern("'Mkz''':.@5"); - assertEquals("Wrong output", "Mkz':.@5", format.format(new Date())); - - //assertTrue("Tests failed", !test.testsFailed()); - - // Test invalid args to format. - SimpleDateFormat dateFormat = new SimpleDateFormat(); - try { - dateFormat.format(null, new StringBuffer(), new FieldPosition(1)); - fail("Expected test to throw NPE."); - } catch (NullPointerException ex) { - // expected - } catch (Throwable ex) { - fail("Expected test to throw NPE, not " + ex.getClass().getName()); - } - - assertFalse(test.testsFailed); - } - - /** - * This test assumes Unicode behavior where 'y' and 'yyy' don't truncate, - * which means that it will fail on the RI. - */ - public void testFormattingYear() { - FormatTester test = new FormatTester(); - - Calendar cal = new GregorianCalendar(1999, Calendar.JUNE, 2, 15, 3, 6); - test.test(" y", cal, " 1999", DateFormat.YEAR_FIELD); - test.test(" yy", cal, " 99", DateFormat.YEAR_FIELD); - test.test(" yy", new GregorianCalendar(2001, Calendar.JUNE, 2), " 01", - DateFormat.YEAR_FIELD); - test.test(" yy", new GregorianCalendar(2000, Calendar.JUNE, 2), " 00", - DateFormat.YEAR_FIELD); - test.test(" yyy", new GregorianCalendar(2000, Calendar.JUNE, 2), " 2000", - DateFormat.YEAR_FIELD); - test.test(" yyy", cal, " 1999", DateFormat.YEAR_FIELD); - test.test(" yyyy", cal, " 1999", DateFormat.YEAR_FIELD); - test.test(" yyyyy", cal, " 01999", DateFormat.YEAR_FIELD); - - assertFalse(test.testsFailed); - } - - public void testFormattingWeekOfYear() { - FormatTester test = new FormatTester(); - Calendar cal = new GregorianCalendar(1999, Calendar.JUNE, 2, 15, 3, 6); - cal.setMinimalDaysInFirstWeek(1); - cal.setFirstDayOfWeek(1); - - test.test(" w", cal, " 23", DateFormat.WEEK_OF_YEAR_FIELD); - test.test(" ww", cal, " 23", DateFormat.WEEK_OF_YEAR_FIELD); - test.test(" wwww", cal, " 0023", DateFormat.WEEK_OF_YEAR_FIELD); - - test.test(" W", cal, " 1", DateFormat.WEEK_OF_MONTH_FIELD); - test.test(" W", new GregorianCalendar(1999, Calendar.NOVEMBER, 14), - " 3", DateFormat.WEEK_OF_MONTH_FIELD); - test.test(" WW", cal, " 01", DateFormat.WEEK_OF_MONTH_FIELD); - test.test(" WWWW", cal, " 0001", DateFormat.WEEK_OF_MONTH_FIELD); - - assertFalse(test.testsFailed); - } - - public void testFormattingTimezones() { - FormatTester test = new FormatTester(); - Calendar cal = new GregorianCalendar(1999, Calendar.JUNE, 2, 15, 3, 6); - - TimeZone tz0001 = new SimpleTimeZone(60000, "ONE MINUTE"); - TimeZone tz0130 = new SimpleTimeZone(5400000, "ONE HOUR, THIRTY"); - TimeZone tzMinus0130 = new SimpleTimeZone(-5400000, "NEG ONE HOUR, THIRTY"); - - format.setTimeZone(tz0001); - test.test(" Z", cal, " +0001", DateFormat.TIMEZONE_FIELD); - test.test(" ZZZZ", cal, " GMT+00:01", DateFormat.TIMEZONE_FIELD); - test.test(" ZZZZZ", cal, " +00:01", DateFormat.TIMEZONE_FIELD); - format.setTimeZone(tz0130); - test.test(" Z", cal, " +0130", DateFormat.TIMEZONE_FIELD); - format.setTimeZone(tzMinus0130); - test.test(" Z", cal, " -0130", DateFormat.TIMEZONE_FIELD); - - format.setTimeZone(tz0001); - test.test(" z", cal, " GMT+00:01", DateFormat.TIMEZONE_FIELD); - test.test(" zzzz", cal, " GMT+00:01", DateFormat.TIMEZONE_FIELD); - format.setTimeZone(tz0130); - test.test(" z", cal, " GMT+01:30", DateFormat.TIMEZONE_FIELD); - format.setTimeZone(tzMinus0130); - test.test(" z", cal, " GMT-01:30", DateFormat.TIMEZONE_FIELD); - - format.setTimeZone(TimeZone.getTimeZone("America/New_York")); - test.test(" z", cal, " EDT", DateFormat.TIMEZONE_FIELD); - Calendar temp2 = new GregorianCalendar(1999, Calendar.JANUARY, 12); - test.test(" z", temp2, " EST", DateFormat.TIMEZONE_FIELD); - test.test(" zz", cal, " EDT", DateFormat.TIMEZONE_FIELD); - test.test(" zzz", cal, " EDT", DateFormat.TIMEZONE_FIELD); - test.test(" zzzz", cal, " Eastern Daylight Time", DateFormat.TIMEZONE_FIELD); - test.test(" zzzz", temp2, " Eastern Standard Time", DateFormat.TIMEZONE_FIELD); - test.test(" zzzzz", cal, " Eastern Daylight Time", DateFormat.TIMEZONE_FIELD); - - assertFalse(test.testsFailed); - } - - /** - * java.text.SimpleDateFormat#format(java.util.Date) - */ - public void test_timeZoneFormatting() { - // tests specific to formatting of timezones - Date summerDate = new GregorianCalendar(1999, Calendar.JUNE, 2, 15, 3, 6).getTime(); - Date winterDate = new GregorianCalendar(1999, Calendar.JANUARY, 12).getTime(); - - FormatTester test = new FormatTester(); - test.verifyFormatTimezone("GMT-7", "GMT-07:00, GMT-07:00", "-0700, GMT-07:00", summerDate); - test.verifyFormatTimezone("GMT-7", "GMT-07:00, GMT-07:00", "-0700, GMT-07:00", winterDate); - - test.verifyFormatTimezone("GMT+14", "GMT+14:00, GMT+14:00", "+1400, GMT+14:00", summerDate); - test.verifyFormatTimezone("GMT+14", "GMT+14:00, GMT+14:00", "+1400, GMT+14:00", winterDate); - - test.verifyFormatTimezone("America/Los_Angeles", "PDT, Pacific Daylight Time", "-0700, GMT-07:00", summerDate); - test.verifyFormatTimezone("America/Los_Angeles", "PST, Pacific Standard Time", "-0800, GMT-08:00", winterDate); - - // this fails on the RI! - test.verifyFormatTimezone("America/Detroit", "EDT, Eastern Daylight Time", "-0400, GMT-04:00", summerDate); - test.verifyFormatTimezone("America/Detroit", "EST, Eastern Standard Time", "-0500, GMT-05:00", winterDate); - - assertFalse(test.testsFailed); - } - - public void test_parseLjava_lang_StringLjava_text_ParsePosition_2() { - try { - format.parse("240 11 2002 March", null); - fail("ParsePosition is null: NullPointerException was not thrown."); - } catch(NullPointerException pe) { - //expected - } - - try { - format.parse(null, new ParsePosition(0)); - fail("String is null: NullPointerException was not thrown."); - } catch(NullPointerException pe) { - //expected - } - } - - public void test_setDateFormatSymbolsLjava_text_DateFormatSymbols() { - // Test for method void - // java.text.SimpleDateFormat.setDateFormatSymbols(java.text.DateFormatSymbols) - SimpleDateFormat f1 = new SimpleDateFormat("a"); - DateFormatSymbols symbols = new DateFormatSymbols(); - symbols.setAmPmStrings(new String[] { "morning", "night" }); - f1.setDateFormatSymbols(symbols); - DateFormatSymbols newSym = f1.getDateFormatSymbols(); - assertTrue("Set incorrectly", newSym.equals(symbols)); - assertTrue("Not a clone", f1.getDateFormatSymbols() != symbols); - String result = f1.format(new GregorianCalendar(1999, Calendar.JUNE, - 12, 3, 0).getTime()); - assertEquals("Incorrect symbols used", "morning", result); - symbols.setEras(new String[] { "before", "after" }); - assertTrue("Identical symbols", !f1.getDateFormatSymbols().equals( - symbols)); - - try { - f1.setDateFormatSymbols(null); - fail("NullPointerException was not thrown."); - } catch(NullPointerException npe) { - //expected - } - } - - public void test_toLocalizedPattern() { - // BEGIN android-changed - // Test for method java.lang.String - // java.text.SimpleDateFormat.toLocalizedPattern() - SimpleDateFormat f2 = new SimpleDateFormat("GyMdkHmsSEDFwWahKzZ", - new Locale("de", "CH")); - String pattern = f2.toLocalizedPattern(); - // the default localized pattern characters are the same for all locales - // since icu has dropped support for this. the default pattern characters - // are these: GyMdkHmsSEDFwWahKz - // ICU only! this fails on the RI - assertTrue("Wrong pattern: " + pattern, pattern - .equals("GyMdkHmsSEDFwWahKzZ")); - - - // test the new "Z" pattern char - f2 = new SimpleDateFormat("G y M d Z", new Locale("de", "CH")); - pattern = f2.toLocalizedPattern(); - // assertTrue("Wrong pattern: " + pattern, pattern.equals("G u M t Z")); - assertTrue("Wrong pattern: " + pattern, pattern.equals("G y M d Z")); - // END android-changed - } - - public void test_toPattern() { - String pattern = "yyyy mm dd"; - SimpleDateFormat f = new SimpleDateFormat(pattern); - assertEquals("Wrong pattern: " + pattern, pattern, f.toPattern()); - - pattern = "GyMdkHmsSEDFwWahKz"; - f = new SimpleDateFormat("GyMdkHmsSEDFwWahKz", new Locale("de", "CH")); - assertTrue("Wrong pattern: " + pattern, f.toPattern().equals(pattern)); - - pattern = "G y M d Z"; - f = new SimpleDateFormat(pattern, new Locale("de", "CH")); - pattern = f.toPattern(); - assertTrue("Wrong pattern: " + pattern, f.toPattern().equals(pattern)); - } -} diff --git a/luni/src/test/java/libcore/java/text/SimpleDateFormatTest.java b/luni/src/test/java/libcore/java/text/SimpleDateFormatTest.java index 2813cee..e73104d 100644 --- a/luni/src/test/java/libcore/java/text/SimpleDateFormatTest.java +++ b/luni/src/test/java/libcore/java/text/SimpleDateFormatTest.java @@ -80,27 +80,12 @@ public class SimpleDateFormatTest extends junit.framework.TestCase { // The RI fails this test because it doesn't fully support UTS #35. // https://code.google.com/p/android/issues/detail?id=39616 public void testFiveCount_parsing() throws Exception { - // It's pretty silly to try to parse the shortest names, because they're almost always ambiguous. - try { - parseDate(Locale.ENGLISH, "MMMMM", "J"); - fail(); - } catch (junit.framework.AssertionFailedError expected) { - } - try { - parseDate(Locale.ENGLISH, "LLLLL", "J"); - fail(); - } catch (junit.framework.AssertionFailedError expected) { - } - try { - parseDate(Locale.ENGLISH, "EEEEE", "T"); - fail(); - } catch (junit.framework.AssertionFailedError expected) { - } - try { - parseDate(Locale.ENGLISH, "ccccc", "T"); - fail(); - } catch (junit.framework.AssertionFailedError expected) { - } + // It's pretty silly to try to parse the shortest names, because they're almost always + // ambiguous. + assertCannotParse(Locale.ENGLISH, "MMMMM", "J"); + assertCannotParse(Locale.ENGLISH, "LLLLL", "J"); + assertCannotParse(Locale.ENGLISH, "EEEEE", "T"); + assertCannotParse(Locale.ENGLISH, "ccccc", "T"); } // The RI fails this test because it doesn't fully support UTS #35. @@ -197,6 +182,13 @@ public class SimpleDateFormatTest extends junit.framework.TestCase { return dateFormat.format(new Date(0)); } + private static void assertCannotParse(Locale l, String fmt, String value) { + SimpleDateFormat sdf = new SimpleDateFormat(fmt, l); + ParsePosition pp = new ParsePosition(0); + Date d = sdf.parse(value, pp); + assertNull("Value " + value + " must not parse in locale " + l + " with format " + fmt, d); + } + private static Calendar parseDate(Locale l, String fmt, String value) { SimpleDateFormat sdf = new SimpleDateFormat(fmt, l); ParsePosition pp = new ParsePosition(0); @@ -215,21 +207,37 @@ public class SimpleDateFormatTest extends junit.framework.TestCase { String date = "2010-12-23 12:44:57.0 CET"; // ICU considers "CET" (Central European Time) to be common in Britain... assertEquals(1293104697000L, parseDate(Locale.UK, fmt, date).getTimeInMillis()); - // ...but not in the US. Check we can parse such a date anyway. - assertEquals(1293104697000L, parseDate(Locale.US, fmt, date).getTimeInMillis()); + // ...but not in the US. + assertCannotParse(Locale.US, fmt, date); } + // In Honeycomb, only one Olson id was associated with CET (or any other "uncommon" + // abbreviation). This was changed after KitKat to avoid Java hacks on top of ICU data. + // ICU data only provides abbreviations for timezones in the locales where they would + // not be ambiguous to most people of that locale. public void testFormattingUncommonTimeZoneAbbreviations() { - // In Honeycomb, only one Olson id was associated with CET (or any - // other "uncommon" abbreviation). String fmt = "yyyy-MM-dd HH:mm:ss.SSS z"; - String date = "1970-01-01 01:00:00.000 CET"; - SimpleDateFormat sdf = new SimpleDateFormat(fmt, Locale.US); + String unambiguousDate = "1970-01-01 01:00:00.000 CET"; + String ambiguousDate = "1970-01-01 01:00:00.000 GMT+01:00"; + + // The locale to use when formatting. Not every Locale renders "Europe/Berlin" as "CET". The + // UK is one that does, the US is one that does not. + Locale cetUnambiguousLocale = Locale.UK; + Locale cetAmbiguousLocale = Locale.US; + + SimpleDateFormat sdf = new SimpleDateFormat(fmt, cetUnambiguousLocale); + sdf.setTimeZone(TimeZone.getTimeZone("Europe/Berlin")); + assertEquals(unambiguousDate, sdf.format(new Date(0))); + sdf = new SimpleDateFormat(fmt, cetUnambiguousLocale); + sdf.setTimeZone(TimeZone.getTimeZone("Europe/Zurich")); + assertEquals(unambiguousDate, sdf.format(new Date(0))); + + sdf = new SimpleDateFormat(fmt, cetAmbiguousLocale); sdf.setTimeZone(TimeZone.getTimeZone("Europe/Berlin")); - assertEquals(date, sdf.format(new Date(0))); - sdf = new SimpleDateFormat(fmt, Locale.US); + assertEquals(ambiguousDate, sdf.format(new Date(0))); + sdf = new SimpleDateFormat(fmt, cetAmbiguousLocale); sdf.setTimeZone(TimeZone.getTimeZone("Europe/Zurich")); - assertEquals(date, sdf.format(new Date(0))); + assertEquals(ambiguousDate, sdf.format(new Date(0))); } // http://code.google.com/p/android/issues/detail?id=8258 @@ -270,17 +278,6 @@ public class SimpleDateFormatTest extends junit.framework.TestCase { assertEquals("2010-07-08T02:44:48+0000", sdf.format(date)); } - /** - * Africa/Cairo standard time is EET and daylight time is EEST. They no - * longer use their DST zone but we should continue to parse it properly. - */ - public void testObsoleteDstZoneName() throws Exception { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm zzzz", Locale.US); - Date normal = format.parse("1970-01-01T00:00 EET"); - Date dst = format.parse("1970-01-01T00:00 EEST"); - assertEquals(60 * 60 * 1000, normal.getTime() - dst.getTime()); - } - public void testDstZoneNameWithNonDstTimestamp() throws Exception { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm zzzz", Locale.US); Calendar calendar = new GregorianCalendar(AMERICA_LOS_ANGELES); @@ -353,4 +350,32 @@ public class SimpleDateFormatTest extends junit.framework.TestCase { assertEquals(1376927400000L, sdf.parse("19. Aug 2013 8:50").getTime()); assertEquals(1376927400000L, sdf.parse("19. Aug. 2013 8:50").getTime()); } + + // http://b/16969112 + public void test_fractionalSeconds() throws Exception { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); + assertEquals("1970-01-02 02:17:36.7", sdf.format(sdf.parse("1970-01-02 02:17:36.7"))); + + // We only have millisecond precision for Date objects, so we'll lose + // information from the fractional seconds section of the string presentation. + sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS"); + assertEquals("1970-01-02 02:17:36.789000", sdf.format(sdf.parse("1970-01-02 02:17:36.789564"))); + } + + public void test_nullLocales() { + try { + SimpleDateFormat.getDateInstance(DateFormat.SHORT, null); + fail(); + } catch (NullPointerException expected) {} + + try { + SimpleDateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, null); + fail(); + } catch (NullPointerException expected) {} + + try { + SimpleDateFormat.getTimeInstance(DateFormat.SHORT, null); + fail(); + } catch (NullPointerException expected) {} + } } diff --git a/luni/src/test/java/libcore/java/util/AbstractResourceLeakageDetectorTestCase.java b/luni/src/test/java/libcore/java/util/AbstractResourceLeakageDetectorTestCase.java new file mode 100644 index 0000000..5ea67d3 --- /dev/null +++ b/luni/src/test/java/libcore/java/util/AbstractResourceLeakageDetectorTestCase.java @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2014 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.util; + +import junit.framework.TestCase; + +/** + * Ensures that resources used within a test are cleaned up; will detect problems with tests and + * also with runtime. + */ +public abstract class AbstractResourceLeakageDetectorTestCase extends TestCase { + /** + * The leakage detector. + */ + private ResourceLeakageDetector detector; + + @Override + protected void setUp() throws Exception { + detector = ResourceLeakageDetector.newDetector(); + } + + @Override + protected void tearDown() throws Exception { + // If available check for resource leakage. At this point it is impossible to determine + // whether the test has thrown an exception. If it has then the exception thrown by this + // could hide that test failure; it largely depends on the test runner. + if (detector != null) { + detector.checkForLeaks(); + } + } +} diff --git a/luni/src/test/java/libcore/java/util/CalendarTest.java b/luni/src/test/java/libcore/java/util/CalendarTest.java index dd44789..e0e1a35 100644 --- a/luni/src/test/java/libcore/java/util/CalendarTest.java +++ b/luni/src/test/java/libcore/java/util/CalendarTest.java @@ -17,6 +17,7 @@ package libcore.java.util; import java.util.Calendar; +import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; @@ -187,8 +188,10 @@ public class CalendarTest extends junit.framework.TestCase { + "10000000500000001000000200000000178"; Calendar calendar = new GregorianCalendar(1970, 1, 1, 0, 0, 0); calendar.setTimeZone(TimeZone.getTimeZone("GMT-08:00")); - // Starting from ICU4.8 release, the default minimalDaysInFirstWeek changed from 4 to 1. + // Calendar fields firstDayOfWeek and minimalDaysInFirstWeek are are sensitive to the Locale + // and ICU data. Specifying the values here makes the serialized form stable. calendar.setMinimalDaysInFirstWeek(4); + calendar.setFirstDayOfWeek(Calendar.SUNDAY); new SerializationTester<Calendar>(calendar, s).test(); } @@ -236,4 +239,28 @@ public class CalendarTest extends junit.framework.TestCase { cal.set(Calendar.HOUR_OF_DAY, 1); assertEquals(32400000, cal.getTimeInMillis()); } + + // http://b/16938922. + // + // TODO: This is for backwards compatibility only. Seems like a better idea to throw + // here. We should add a targetSdkVersion based check and throw for each of these + // cases. + public void test_nullLocale() { + assertCalendarConfigEquals( + Calendar.getInstance(Locale.getDefault()), + Calendar.getInstance((Locale) null)); + assertCalendarConfigEquals( + Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault()), + Calendar.getInstance(TimeZone.getDefault(), null)); + assertCalendarConfigEquals( + new GregorianCalendar(Locale.getDefault()), + new GregorianCalendar((Locale) null)); + } + + public void assertCalendarConfigEquals(Calendar a, Calendar b) { + Date d = new Date(); + a.setTime(d); + b.setTime(d); + assertEquals(a, b); + } } diff --git a/luni/src/test/java/libcore/java/util/CurrencyTest.java b/luni/src/test/java/libcore/java/util/CurrencyTest.java index 61a22fd..cf2a1b6 100644 --- a/luni/src/test/java/libcore/java/util/CurrencyTest.java +++ b/luni/src/test/java/libcore/java/util/CurrencyTest.java @@ -79,4 +79,12 @@ public class CurrencyTest extends junit.framework.TestCase { assertEquals("€", Currency.getInstance(pt_PT).getSymbol(pt_BR)); assertEquals("€", Currency.getInstance(pt_PT).getSymbol(pt_PT)); } + + public void test_nullLocales() { + Currency currency = Currency.getInstance(Locale.getDefault()); + try { + currency.getSymbol(null); + fail(); + } catch (NullPointerException expected) {} + } } diff --git a/luni/src/test/java/libcore/java/util/DateTest.java b/luni/src/test/java/libcore/java/util/DateTest.java index ddcc3e5..3ed0952 100644 --- a/luni/src/test/java/libcore/java/util/DateTest.java +++ b/luni/src/test/java/libcore/java/util/DateTest.java @@ -24,16 +24,26 @@ import junit.framework.TestCase; public class DateTest extends TestCase { // http://code.google.com/p/android/issues/detail?id=6013 - public void test_toString() throws Exception { - // Ensure that no matter where this is run, we know what time zone - // to expect. (Though we still assume an "en" locale.) + public void test_toString_us() throws Exception { + // Ensure that no matter where this is run, we know what time zone to expect. + Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("America/Chicago")); assertEquals("Wed Dec 31 18:00:00 CST 1969", new Date(0).toString()); } - public void test_toGMTString() throws Exception { + public void test_toString_nonUs() { + // The string for the timezone depends on what the default locale is. Not every locale + // has a short-name for America/Chicago -> PST. + Locale.setDefault(Locale.UK); + TimeZone.setDefault(TimeZone.getTimeZone("America/Chicago")); + assertEquals("Wed Dec 31 18:00:00 GMT-06:00 1969", new Date(0).toString()); + } + + public void test_toGMTString_us() throws Exception { // Based on https://issues.apache.org/jira/browse/HARMONY-501 TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles")); + Locale.setDefault(Locale.US); + Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 21); @@ -43,4 +53,18 @@ public class DateTest extends TestCase { assertEquals("Sun Jan 01 00:00:00 PST 321", c.getTime().toString()); assertEquals("1 Jan 321 08:00:00 GMT", c.getTime().toGMTString()); } + + public void test_toGMTString_nonUs() throws Exception { + TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles")); + Locale.setDefault(Locale.UK); + + Calendar c = Calendar.getInstance(); + c.clear(); + c.set(Calendar.YEAR, 21); + assertEquals("Wed Jan 01 00:00:00 GMT-08:00 21", c.getTime().toString()); + assertEquals("1 Jan 21 08:00:00 GMT", c.getTime().toGMTString()); + c.set(Calendar.YEAR, 321); + assertEquals("Sun Jan 01 00:00:00 GMT-08:00 321", c.getTime().toString()); + assertEquals("1 Jan 321 08:00:00 GMT", c.getTime().toGMTString()); + } } diff --git a/luni/src/test/java/libcore/java/util/GregorianCalendarTest.java b/luni/src/test/java/libcore/java/util/GregorianCalendarTest.java new file mode 100644 index 0000000..b2c50b2 --- /dev/null +++ b/luni/src/test/java/libcore/java/util/GregorianCalendarTest.java @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2013 Google Inc. + * + * 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.util; + + +import junit.framework.TestCase; +import java.util.Calendar; +import java.util.GregorianCalendar; + +public class GregorianCalendarTest extends TestCase { + + // https://code.google.com/p/android/issues/detail?id=61993 + public void test_computeFields_dayOfWeekAndWeekOfYearSet() { + Calendar greg = GregorianCalendar.getInstance(); + + // Setting WEEK_OF_YEAR and DAY_OF_WEEK with an intervening + // call to computeFields will work. + greg.set(Calendar.WEEK_OF_YEAR, 1); + assertEquals(1, greg.get(Calendar.WEEK_OF_YEAR)); + greg.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); + assertEquals(1, greg.get(Calendar.WEEK_OF_YEAR)); + + // Setting WEEK_OF_YEAR after DAY_OF_WEEK with no intervening + // call to computeFields will work. + greg = GregorianCalendar.getInstance(); + greg.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); + greg.set(Calendar.WEEK_OF_YEAR, 1); + assertEquals(1, greg.get(Calendar.WEEK_OF_YEAR)); + assertEquals(Calendar.MONDAY, greg.get(Calendar.DAY_OF_WEEK)); + + // Setting DAY_OF_WEEK *after* WEEK_OF_YEAR with no intervening computeFields + // will make WEEK_OF_YEAR have no effect. This is a limitation of the API. + // Combinations are chosen based *only* on the value of the last field set, + // which in this case is DAY_OF_WEEK. + greg = GregorianCalendar.getInstance(); + int weekOfYear = greg.get(Calendar.WEEK_OF_YEAR); + greg.set(Calendar.WEEK_OF_YEAR, 1); + greg.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); + // Unchanged WEEK_OF_YEAR. + assertEquals(weekOfYear, greg.get(Calendar.WEEK_OF_YEAR)); + } +} diff --git a/luni/src/test/java/libcore/java/util/LocaleInternalsTest.java b/luni/src/test/java/libcore/java/util/LocaleInternalsTest.java new file mode 100644 index 0000000..5344f08 --- /dev/null +++ b/luni/src/test/java/libcore/java/util/LocaleInternalsTest.java @@ -0,0 +1,129 @@ +/* + * Copyright (C) 2014 Google Inc. + * + * 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.util; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import junit.framework.TestCase; +import libcore.icu.ICU; + +public class LocaleInternalsTest extends TestCase { + + public void test_serializeExtensions() { + Map<Character, String> extensions = new TreeMap<Character, String>(); + + extensions.put('x', "fooo-baar-baaz"); + assertEquals("x-fooo-baar-baaz", Locale.serializeExtensions(extensions)); + + extensions.put('y', "gaaa-caar-caaz"); + // Must show up in lexical order. + assertEquals("x-fooo-baar-baaz-y-gaaa-caar-caaz", + Locale.serializeExtensions(extensions)); + } + + public void test_parseSerializedExtensions() { + Map<Character, String> extensions = new HashMap<Character, String>(); + + Locale.parseSerializedExtensions("x-foo", extensions); + assertEquals("foo", extensions.get('x')); + + extensions.clear(); + Locale.parseSerializedExtensions("x-foo-y-bar-z-baz", extensions); + assertEquals("foo", extensions.get('x')); + assertEquals("bar", extensions.get('y')); + assertEquals("baz", extensions.get('z')); + + extensions.clear(); + Locale.parseSerializedExtensions("x-fooo-baar-baaz", extensions); + assertEquals("fooo-baar-baaz", extensions.get('x')); + + extensions.clear(); + Locale.parseSerializedExtensions("x-fooo-baar-baaz-y-gaaa-caar-caaz", extensions); + assertEquals("fooo-baar-baaz", extensions.get('x')); + assertEquals("gaaa-caar-caaz", extensions.get('y')); + } + + public void test_parseUnicodeExtension() { + Map<String, String> keywords = new HashMap<String, String>(); + Set<String> attributes = new HashSet<String>(); + + // Only attributes. + Locale.parseUnicodeExtension("foooo".split("-"), keywords, attributes); + assertTrue(attributes.contains("foooo")); + assertEquals(Collections.EMPTY_SET, keywords.keySet()); + + attributes.clear(); + keywords.clear(); + Locale.parseUnicodeExtension("foooo-baa-baaabaaa".split("-"), + keywords, attributes); + assertTrue(attributes.contains("foooo")); + assertTrue(attributes.contains("baa")); + assertTrue(attributes.contains("baaabaaa")); + assertEquals(Collections.EMPTY_SET, keywords.keySet()); + + // Only keywords + attributes.clear(); + keywords.clear(); + Locale.parseUnicodeExtension("ko-koko".split("-"), keywords, attributes); + assertTrue(attributes.isEmpty()); + assertEquals("koko", keywords.get("ko")); + + attributes.clear(); + keywords.clear(); + Locale.parseUnicodeExtension("ko-koko-kokoko".split("-"), keywords, attributes); + assertTrue(attributes.isEmpty()); + assertEquals("koko-kokoko", keywords.get("ko")); + + attributes.clear(); + keywords.clear(); + Locale.parseUnicodeExtension("ko-koko-kokoko-ba-baba-bababa".split("-"), + keywords, attributes); + assertTrue(attributes.isEmpty()); + assertEquals("koko-kokoko", keywords.get("ko")); + assertEquals("baba-bababa", keywords.get("ba")); + + // A mixture of attributes and keywords. + attributes.clear(); + keywords.clear(); + Locale.parseUnicodeExtension("attri1-attri2-k1-type1-type1-k2-type2".split("-"), + keywords, attributes); + assertTrue(attributes.contains("attri1")); + assertTrue(attributes.contains("attri2")); + assertEquals("type1-type1", keywords.get("k1")); + assertEquals("type2", keywords.get("k2")); + } + + public void test_setDefault_setsICUDefaultLocale() { + Locale.setDefault(Locale.GERMANY); + assertEquals("de_DE", ICU.getDefaultLocale()); + + try { + Locale.setDefault(null); + fail(); + } catch (NullPointerException expected) { + assertEquals(Locale.GERMANY, Locale.getDefault()); + } + + Locale.setDefault(new Locale("bogus", "LOCALE")); + assertEquals("und", ICU.getDefaultLocale()); + } +} diff --git a/luni/src/test/java/libcore/java/util/LocaleTest.java b/luni/src/test/java/libcore/java/util/LocaleTest.java index dee529f..c72ecd7 100644 --- a/luni/src/test/java/libcore/java/util/LocaleTest.java +++ b/luni/src/test/java/libcore/java/util/LocaleTest.java @@ -20,10 +20,9 @@ import java.text.BreakIterator; import java.text.Collator; import java.text.DateFormat; import java.text.DateFormatSymbols; -import java.text.DecimalFormatSymbols; import java.text.NumberFormat; -import java.util.Arrays; import java.util.Calendar; +import java.util.IllformedLocaleException; import java.util.Locale; import java.util.MissingResourceException; @@ -40,9 +39,22 @@ public class LocaleTest extends junit.framework.TestCase { // and variant, but a display name made up of the raw strings. // Newer releases return slightly different results, but no less unreasonable. assertEquals("aabbcc", invalid.getDisplayLanguage()); - assertEquals("", invalid.getDisplayCountry()); - assertEquals("DDEEFF_GGHHII", invalid.getDisplayVariant()); - assertEquals("aabbcc (DDEEFF,DDEEFF_GGHHII)", invalid.getDisplayName()); + assertEquals("DDEEFF", invalid.getDisplayCountry()); + assertEquals("GGHHII", invalid.getDisplayVariant()); + assertEquals("aabbcc (DDEEFF,GGHHII)", invalid.getDisplayName()); + } + + public void test_getDisplayName_emptyCodes() { + Locale emptyLanguage = new Locale("", "DdeEFf"); + assertEquals("", emptyLanguage.getDisplayLanguage()); + + Locale emptyCountry = new Locale("AaBbCc", ""); + assertEquals("", emptyCountry.getDisplayCountry()); + + Locale emptyCountryAndLanguage = new Locale("", "", "Farl"); + assertEquals("", emptyCountryAndLanguage.getDisplayLanguage()); + assertEquals("", emptyCountryAndLanguage.getDisplayCountry()); + assertEquals("Farl", emptyCountryAndLanguage.getDisplayVariant()); } // http://b/2611311; if there's no display language/country/variant, use the raw codes. @@ -54,8 +66,8 @@ public class LocaleTest extends junit.framework.TestCase { assertEquals("xx", unknown.getDisplayLanguage()); assertEquals("YY", unknown.getDisplayCountry()); - assertEquals("TRADITIONAL", unknown.getDisplayVariant()); - assertEquals("xx (YY,TRADITIONAL)", unknown.getDisplayName()); + assertEquals("Traditional", unknown.getDisplayVariant()); + assertEquals("xx (YY,Traditional)", unknown.getDisplayName()); } public void test_getDisplayName_easy() throws Exception { @@ -65,36 +77,68 @@ public class LocaleTest extends junit.framework.TestCase { assertEquals("Deutsch", Locale.GERMAN.getDisplayLanguage(Locale.GERMAN)); } + // https://b/issue?id=13790528 + public void test_getDisplayName_withScriptsAndVariants() throws Exception { + // Script + Country. + assertEquals("Chinese (Traditional Han,China)", + Locale.forLanguageTag("zh-Hant-CN").getDisplayName(Locale.US)); + // Script + Variant. + assertEquals("Chinese (Traditional Han,VARIANT)", + Locale.forLanguageTag("zh-Hant-VARIANT").getDisplayName(Locale.US)); + // Country + Variant. + assertEquals("Chinese (China,VARIANT)", + Locale.forLanguageTag("zh-CN-VARIANT").getDisplayName(Locale.US)); + // Script + Country + variant. + assertEquals("Chinese (Traditional Han,China,VARIANT)", + Locale.forLanguageTag("zh-Hant-CN-VARIANT").getDisplayName(Locale.US)); + } + public void test_getDisplayCountry_8870289() throws Exception { assertEquals("Hong Kong", new Locale("", "HK").getDisplayCountry(Locale.US)); assertEquals("Macau", new Locale("", "MO").getDisplayCountry(Locale.US)); assertEquals("Palestine", new Locale("", "PS").getDisplayCountry(Locale.US)); - assertEquals("Cocos [Keeling] Islands", new Locale("", "CC").getDisplayCountry(Locale.US)); - assertEquals("Congo [DRC]", new Locale("", "CD").getDisplayCountry(Locale.US)); - assertEquals("Congo [Republic]", new Locale("", "CG").getDisplayCountry(Locale.US)); - assertEquals("Falkland Islands [Islas Malvinas]", new Locale("", "FK").getDisplayCountry(Locale.US)); - assertEquals("Macedonia [FYROM]", new Locale("", "MK").getDisplayCountry(Locale.US)); - assertEquals("Myanmar [Burma]", new Locale("", "MM").getDisplayCountry(Locale.US)); + assertEquals("Cocos (Keeling) Islands", new Locale("", "CC").getDisplayCountry(Locale.US)); + assertEquals("Congo (DRC)", new Locale("", "CD").getDisplayCountry(Locale.US)); + assertEquals("Congo (Republic)", new Locale("", "CG").getDisplayCountry(Locale.US)); + assertEquals("Falkland Islands (Islas Malvinas)", new Locale("", "FK").getDisplayCountry(Locale.US)); + assertEquals("Macedonia (FYROM)", new Locale("", "MK").getDisplayCountry(Locale.US)); + assertEquals("Myanmar (Burma)", new Locale("", "MM").getDisplayCountry(Locale.US)); assertEquals("Taiwan", new Locale("", "TW").getDisplayCountry(Locale.US)); } - public void test_tl() throws Exception { + public void test_tl_and_fil() throws Exception { // In jb-mr1, we had a last-minute hack to always return "Filipino" because - // icu4c 4.8 didn't have any localizations for fil. (http://b/7291355) + // icu4c 4.8 didn't have any localizations for fil. (http://b/7291355). + // + // After the icu4c 4.9 upgrade, we could localize "fil" correctly, though we + // needed another hack to supply "fil" instead of "tl" to icu4c. (http://b/8023288). + // + // These hacks have now been reverted, so "tl" really does represent + // tagalog and not filipino. Locale tl = new Locale("tl"); Locale tl_PH = new Locale("tl", "PH"); - assertEquals("Filipino", tl.getDisplayLanguage(Locale.ENGLISH)); - assertEquals("Filipino", tl_PH.getDisplayLanguage(Locale.ENGLISH)); - assertEquals("Filipino", tl.getDisplayLanguage(tl)); - assertEquals("Filipino", tl_PH.getDisplayLanguage(tl_PH)); + assertEquals("Tagalog", tl.getDisplayLanguage(Locale.ENGLISH)); + assertEquals("Tagalog", tl_PH.getDisplayLanguage(Locale.ENGLISH)); + assertEquals("tl", tl.getDisplayLanguage(tl)); + assertEquals("tl", tl_PH.getDisplayLanguage(tl_PH)); - // After the icu4c 4.9 upgrade, we could localize "fil" correctly, though we - // needed another hack to supply "fil" instead of "tl" to icu4c. (http://b/8023288) Locale es_MX = new Locale("es", "MX"); - assertEquals("filipino", tl.getDisplayLanguage(es_MX)); - assertEquals("filipino", tl_PH.getDisplayLanguage(es_MX)); - } + assertEquals("tagalo", tl.getDisplayLanguage(es_MX)); + assertEquals("tagalo", tl_PH.getDisplayLanguage(es_MX)); + + // Assert that we can deal with "fil" correctly, since we've switched + // to using "fil" for Filipino, and not "tl". (http://b/15873165). + Locale fil = new Locale("fil"); + Locale fil_PH = new Locale("fil", "PH"); + assertEquals("Filipino", fil.getDisplayLanguage(Locale.ENGLISH)); + assertEquals("Filipino", fil_PH.getDisplayLanguage(Locale.ENGLISH)); + assertEquals("Filipino", fil.getDisplayLanguage(fil)); + assertEquals("Filipino", fil_PH.getDisplayLanguage(fil_PH)); + + assertEquals("filipino", fil.getDisplayLanguage(es_MX)); + assertEquals("filipino", fil_PH.getDisplayLanguage(es_MX)); + } // http://b/3452611; Locale.getDisplayLanguage fails for the obsolete language codes. public void test_getDisplayName_obsolete() throws Exception { @@ -158,6 +202,10 @@ public class LocaleTest extends junit.framework.TestCase { assertEquals("CAN", new Locale("", "CA").getISO3Country()); assertEquals("CAN", new Locale("en", "CA").getISO3Country()); assertEquals("CAN", new Locale("xx", "CA").getISO3Country()); + + // 3 letter country codes. + assertEquals("CAN", new Locale("en", "CAN").getISO3Country()); + assertEquals("CAN", new Locale("frankenderp", "CAN").getISO3Country()); } public void test_getISO3Language() { @@ -177,5 +225,925 @@ public class LocaleTest extends junit.framework.TestCase { assertEquals("eng", new Locale("en", "").getISO3Language()); assertEquals("eng", new Locale("en", "CA").getISO3Language()); assertEquals("eng", new Locale("en", "XX").getISO3Language()); + + // 3 letter language code. + assertEquals("eng", new Locale("eng", "USA").getISO3Language()); + assertEquals("eng", new Locale("eng", "US").getISO3Language()); + } + + public void test_Builder_setLanguage() { + Locale.Builder b = new Locale.Builder(); + + // Should normalize to lower case. + b.setLanguage("EN"); + assertEquals("en", b.build().getLanguage()); + + b = new Locale.Builder(); + + // Too short. + try { + b.setLanguage("e"); + fail(); + } catch (IllformedLocaleException expected) { + } + + // Too long + try { + b.setLanguage("engl"); + fail(); + } catch (IllformedLocaleException expected) { + } + + // Contains non ASCII characters + try { + b.setLanguage("தமிழ்"); + fail(); + } catch (IllformedLocaleException expected) { + } + + // Null or empty languages must clear state. + b = new Locale.Builder(); + b.setLanguage("en"); + b.setLanguage(null); + assertEquals("", b.build().getLanguage()); + + b = new Locale.Builder(); + b.setLanguage("en"); + b.setLanguage(""); + assertEquals("", b.build().getLanguage()); + } + + public void test_Builder_setRegion() { + Locale.Builder b = new Locale.Builder(); + + // Should normalize to upper case. + b.setRegion("us"); + assertEquals("US", b.build().getCountry()); + + b = new Locale.Builder(); + + // Too short. + try { + b.setRegion("e"); + fail(); + } catch (IllformedLocaleException expected) { + } + + // Too long + try { + b.setRegion("USA"); + fail(); + } catch (IllformedLocaleException expected) { + } + + // Contains non ASCII characters + try { + b.setLanguage("திழ்"); + fail(); + } catch (IllformedLocaleException expected) { + } + + // Null or empty regions must clear state. + b = new Locale.Builder(); + b.setRegion("US"); + b.setRegion(null); + assertEquals("", b.build().getCountry()); + + b = new Locale.Builder(); + b.setRegion("US"); + b.setRegion(""); + assertEquals("", b.build().getCountry()); + } + + public void test_Builder_setVariant() { + Locale.Builder b = new Locale.Builder(); + + // Should normalize "_" to "-" + b = new Locale.Builder(); + b.setVariant("vArIaNt-VaRiAnT-VARIANT"); + assertEquals("vArIaNt_VaRiAnT_VARIANT", b.build().getVariant()); + + b = new Locale.Builder(); + // Too short + try { + b.setVariant("shor"); + fail(); + } catch (IllformedLocaleException expected) { + } + + // Too long + try { + b.setVariant("waytoolong"); + fail(); + } catch (IllformedLocaleException expected) { + } + + try { + b.setVariant("foooo-foooo-fo"); + fail(); + } catch (IllformedLocaleException expected) { + } + + // Special case. Variants of length 4 are allowed when the first + // character is a digit. + b.setVariant("0ABC"); + assertEquals("0ABC", b.build().getVariant()); + + b = new Locale.Builder(); + b.setVariant("variant"); + b.setVariant(null); + assertEquals("", b.build().getVariant()); + + b = new Locale.Builder(); + b.setVariant("variant"); + b.setVariant(""); + assertEquals("", b.build().getVariant()); + } + + public void test_Builder_setLocale() { + // Default case. + Locale.Builder b = new Locale.Builder(); + b.setLocale(Locale.US); + assertEquals("en", b.build().getLanguage()); + assertEquals("US", b.build().getCountry()); + + // Should throw when locale is malformed. + // - Bad language + Locale bad = new Locale("e", "US"); + b = new Locale.Builder(); + try { + b.setLocale(bad); + fail(); + } catch (IllformedLocaleException expected) { + } + // - Bad country + bad = new Locale("en", "USA"); + try { + b.setLocale(bad); + fail(); + } catch (IllformedLocaleException expected) { + } + + // - Bad variant + bad = new Locale("en", "US", "c"); + try { + b.setLocale(bad); + fail(); + } catch (IllformedLocaleException expected) { + } + + // Test values are normalized as they should be + b = new Locale.Builder(); + Locale good = new Locale("EN", "us", "variant-VARIANT"); + b.setLocale(good); + Locale l = b.build(); + assertEquals("en", l.getLanguage()); + assertEquals("US", l.getCountry()); + assertEquals("variant_VARIANT", l.getVariant()); + + // Test that none of the existing fields are messed with + // if the locale update fails. + b = new Locale.Builder(); + b.setLanguage("fr").setRegion("FR"); + + try { + b.setLocale(bad); + fail(); + } catch (IllformedLocaleException expected) { + } + + l = b.build(); + assertEquals("fr", l.getLanguage()); + assertEquals("FR", l.getCountry()); + } + + public void test_Builder_setScript() { + Locale.Builder b = new Locale.Builder(); + + // Should normalize variants to lower case. + b.setScript("lAtN"); + assertEquals("Latn", b.build().getScript()); + + b = new Locale.Builder(); + // Too short + try { + b.setScript("lat"); + fail(); + } catch (IllformedLocaleException expected) { + } + + // Too long + try { + b.setScript("latin"); + fail(); + } catch (IllformedLocaleException expected) { + } + + b = new Locale.Builder(); + b.setScript("Latn"); + b.setScript(null); + assertEquals("", b.build().getScript()); + + b = new Locale.Builder(); + b.setScript("Latn"); + b.setScript(""); + assertEquals("", b.build().getScript()); + } + + public void test_Builder_clear() { + Locale.Builder b = new Locale.Builder(); + b.setLanguage("en").setScript("Latn").setRegion("US") + .setVariant("POSIX").setExtension('g', "foo") + .setUnicodeLocaleKeyword("fo", "baar") + .addUnicodeLocaleAttribute("baaaaz"); + + Locale l = b.clear().build(); + assertEquals("", l.getLanguage()); + assertEquals("", l.getCountry()); + assertEquals("", l.getVariant()); + assertEquals("", l.getScript()); + assertTrue(l.getExtensionKeys().isEmpty()); + } + + public void test_Builder_setExtension() { + Locale.Builder b = new Locale.Builder(); + b.setExtension('g', "FO_ba-BR_bg"); + + Locale l = b.build(); + assertEquals("fo-ba-br-bg", l.getExtension('g')); + + b = new Locale.Builder(); + + // Too short + try { + b.setExtension('g', "fo-ba-br-x"); + fail(); + } catch (IllformedLocaleException expected) { + } + + // Too long + try { + b.setExtension('g', "fo-ba-br-extension"); + fail(); + } catch (IllformedLocaleException expected) { + } + + // Special case, the private use extension allows single char subtags. + b.setExtension(Locale.PRIVATE_USE_EXTENSION, "fo-ba-br-m"); + l = b.build(); + assertEquals("fo-ba-br-m", l.getExtension('x')); + + // Special case, the unicode locale extension must be parsed into + // its individual components. The correctness of the parse is tested + // in test_parseUnicodeExtension. + b.setExtension(Locale.UNICODE_LOCALE_EXTENSION, "foooo_BaaaR-BA_Baz-bI_BIZ"); + l = b.build(); + // Note that attributes and keywords are sorted alphabetically. + assertEquals("baaar-foooo-ba-baz-bi-biz", l.getExtension('u')); + + assertTrue(l.getUnicodeLocaleAttributes().contains("foooo")); + assertTrue(l.getUnicodeLocaleAttributes().contains("baaar")); + assertEquals("baz", l.getUnicodeLocaleType("ba")); + assertEquals("biz", l.getUnicodeLocaleType("bi")); + } + + public void test_Builder_clearExtensions() { + Locale.Builder b = new Locale.Builder(); + b.setExtension('g', "FO_ba-BR_bg"); + b.setExtension(Locale.PRIVATE_USE_EXTENSION, "fo-ba-br-m"); + b.clearExtensions(); + + assertTrue(b.build().getExtensionKeys().isEmpty()); + } + + private static Locale fromLanguageTag(String languageTag, boolean useBuilder) { + if (useBuilder) { + return (new Locale.Builder().setLanguageTag(languageTag).build()); + } else { + return Locale.forLanguageTag(languageTag); + } + } + + private void test_setLanguageTag_wellFormedsingleSubtag(boolean useBuilder) { + Locale l = fromLanguageTag("en", useBuilder); + assertEquals("en", l.getLanguage()); + + l = fromLanguageTag("eng", useBuilder); + assertEquals("eng", l.getLanguage()); + } + + private void test_setLanguageTag_twoWellFormedSubtags(boolean useBuilder) { + Locale l = fromLanguageTag("en-US", useBuilder); + assertEquals("en", l.getLanguage()); + assertEquals("US", l.getCountry()); + + l = fromLanguageTag("eng-419", useBuilder); + assertEquals("eng", l.getLanguage()); + assertEquals("419", l.getCountry()); + + // Script tags shouldn't be mis-recognized as regions. + l = fromLanguageTag("en-Latn", useBuilder); + assertEquals("en", l.getLanguage()); + assertEquals("", l.getCountry()); + assertEquals("Latn", l.getScript()); + + // Neither should variant tags. + l = fromLanguageTag("en-POSIX", useBuilder); + assertEquals("en", l.getLanguage()); + assertEquals("", l.getCountry()); + assertEquals("", l.getScript()); + assertEquals("POSIX", l.getVariant()); + } + + public void test_Builder_setLanguageTag_malformedTags() { + try { + fromLanguageTag("a", true); + fail(); + } catch (IllformedLocaleException ifle) { + } + + // Three subtags + // lang-region-illformedvariant + try { + fromLanguageTag("en-US-BA", true); + fail(); + } catch (IllformedLocaleException expected) { + } + + // lang-variant-illformedvariant + try { + fromLanguageTag("en-FOOOO-BA", true); + fail(); + } catch (IllformedLocaleException expected) { + } + + // Four or more sub tags + try { + fromLanguageTag("en-US-POSIX-P2", true); + fail(); + } catch (IllformedLocaleException expected) { + } + + try { + fromLanguageTag("en-Latn-US-P2", true); + fail(); + } catch (IllformedLocaleException expected) { + } + + // Extensions + // Ill-formed empty extension. + try { + fromLanguageTag("en-f-f", true); + fail(); + } catch (IllformedLocaleException expected) { + } + + // Ill-formed empty extension. + try { + fromLanguageTag("en-f", true); + fail(); + } catch (IllformedLocaleException expected) { + } + + // Two extension keys in a row (i.e, another case of an ill-formed + // empty exception). + try { + fromLanguageTag("en-f-g-fo-baar", true); + fail(); + } catch (IllformedLocaleException expected) { + } + + // Dangling empty key after a well formed extension. + try { + fromLanguageTag("en-f-fo-baar-g", true); + fail(); + } catch (IllformedLocaleException expected) { + } + + // Ill-formed extension with long subtag. + try { + fromLanguageTag("en-f-fooobaaaz", true); + fail(); + } catch (IllformedLocaleException expected) { + } + } + + private void test_setLanguageTag_threeWellFormedSubtags(boolean useBuilder) { + // lang-region-variant + Locale l = fromLanguageTag("en-US-FOOOO", useBuilder); + assertEquals("en", l.getLanguage()); + assertEquals("US", l.getCountry()); + assertEquals("", l.getScript()); + assertEquals("FOOOO", l.getVariant()); + + // lang-script-variant + l = fromLanguageTag("en-Latn-FOOOO", useBuilder); + assertEquals("en", l.getLanguage()); + assertEquals("", l.getCountry()); + assertEquals("Latn", l.getScript()); + assertEquals("FOOOO", l.getVariant()); + + // lang-script-region + l = fromLanguageTag("en-Latn-US", useBuilder); + assertEquals("en", l.getLanguage()); + assertEquals("US", l.getCountry()); + assertEquals("Latn", l.getScript()); + assertEquals("", l.getVariant()); + + // lang-variant-variant + l = fromLanguageTag("en-FOOOO-BAAAR", useBuilder); + assertEquals("en", l.getLanguage()); + assertEquals("", l.getCountry()); + assertEquals("", l.getScript()); + assertEquals("FOOOO_BAAAR", l.getVariant()); + } + + private void test_setLanguageTag_fourOrMoreWellFormedSubtags(boolean useBuilder) { + // lang-script-region-variant. + Locale l = fromLanguageTag("en-Latn-US-foooo", useBuilder); + assertEquals("en", l.getLanguage()); + assertEquals("Latn", l.getScript()); + assertEquals("US", l.getCountry()); + assertEquals("foooo", l.getVariant()); + + // Variant with multiple subtags. + l = fromLanguageTag("en-Latn-US-foooo-gfffh", useBuilder); + assertEquals("en", l.getLanguage()); + assertEquals("Latn", l.getScript()); + assertEquals("US", l.getCountry()); + assertEquals("foooo_gfffh", l.getVariant()); + + // Variant with 3 subtags. POSIX shouldn't be recognized + // as a region or a script. + l = fromLanguageTag("en-POSIX-P2003-P2004", useBuilder); + assertEquals("en", l.getLanguage()); + assertEquals("", l.getScript()); + assertEquals("", l.getCountry()); + assertEquals("POSIX_P2003_P2004", l.getVariant()); + + // lang-script-variant-variant. + l = fromLanguageTag("en-Latn-POSIX-P2003", useBuilder); + assertEquals("en", l.getLanguage()); + assertEquals("Latn", l.getScript()); + assertEquals("", l.getCountry()); + assertEquals("POSIX_P2003", l.getVariant()); + + // lang-region-variant-variant + l = fromLanguageTag("en-US-POSIX-P2003", useBuilder); + assertEquals("en", l.getLanguage()); + assertEquals("", l.getScript()); + assertEquals("US", l.getCountry()); + assertEquals("POSIX_P2003", l.getVariant()); + } + + private void test_setLanguageTag_withWellFormedExtensions(boolean useBuilder) { + Locale l = fromLanguageTag("en-Latn-GB-foooo-g-fo-bar-baaz", useBuilder); + assertEquals("en", l.getLanguage()); + assertEquals("Latn", l.getScript()); + assertEquals("GB", l.getCountry()); + assertEquals("foooo", l.getVariant()); + assertEquals("fo-bar-baaz", l.getExtension('g')); + + // Multiple extensions + l = fromLanguageTag("en-Latn-US-foooo-g-fo-bar-h-go-gaz", useBuilder); + assertEquals("en", l.getLanguage()); + assertEquals("Latn", l.getScript()); + assertEquals("US", l.getCountry()); + assertEquals("foooo", l.getVariant()); + assertEquals("fo-bar", l.getExtension('g')); + assertEquals("go-gaz", l.getExtension('h')); + + // Unicode locale extension. + l = fromLanguageTag("en-Latn-US-foooo-u-koooo-fo-bar", useBuilder); + assertEquals("en", l.getLanguage()); + assertEquals("Latn", l.getScript()); + assertEquals("US", l.getCountry()); + assertEquals("koooo-fo-bar", l.getExtension('u')); + assertTrue(l.getUnicodeLocaleAttributes().contains("koooo")); + assertEquals("bar", l.getUnicodeLocaleType("fo")); + + // Extensions without variants + l = fromLanguageTag("en-Latn-US-f-fo", useBuilder); + assertEquals("en", l.getLanguage()); + assertEquals("Latn", l.getScript()); + assertEquals("US", l.getCountry()); + assertEquals("fo", l.getExtension('f')); + + l = fromLanguageTag("en-Latn-f-fo", useBuilder); + assertEquals("en", l.getLanguage()); + assertEquals("Latn", l.getScript()); + assertEquals("fo", l.getExtension('f')); + + l = fromLanguageTag("en-f-fo", useBuilder); + assertEquals("en", l.getLanguage()); + assertEquals("", l.getScript()); + assertEquals("", l.getCountry()); + assertEquals("fo", l.getExtension('f')); + + l = fromLanguageTag("en-f-fo-x-a-b-c-d-e-fo", useBuilder); + assertEquals("en", l.getLanguage()); + assertEquals("", l.getScript()); + assertEquals("", l.getCountry()); + assertEquals("fo", l.getExtension('f')); + assertEquals("a-b-c-d-e-fo", l.getExtension('x')); + } + + public void test_forLanguageTag() { + test_setLanguageTag_wellFormedsingleSubtag(false); + test_setLanguageTag_twoWellFormedSubtags(false); + test_setLanguageTag_threeWellFormedSubtags(false); + test_setLanguageTag_fourOrMoreWellFormedSubtags(false); + test_setLanguageTag_withWellFormedExtensions(false); + } + + public void test_Builder_setLanguageTag() { + test_setLanguageTag_wellFormedsingleSubtag(true); + test_setLanguageTag_twoWellFormedSubtags(true); + test_setLanguageTag_threeWellFormedSubtags(true); + test_setLanguageTag_fourOrMoreWellFormedSubtags(true); + test_setLanguageTag_withWellFormedExtensions(true); + } + + public void test_getDisplayScript() { + Locale.Builder b = new Locale.Builder(); + b.setLanguage("en").setRegion("US").setScript("Latn"); + + Locale l = b.build(); + + // getDisplayScript() test relies on the default locale. We set it here to avoid test + // failures if the test device is set to a non-English locale. + Locale.setDefault(Locale.US); + assertEquals("Latin", l.getDisplayScript()); + + assertEquals("Lateinisch", l.getDisplayScript(Locale.GERMAN)); + // Fallback for navajo, a language for which we don't have data. + assertEquals("Latin", l.getDisplayScript(new Locale("nv", "US"))); + + b= new Locale.Builder(); + b.setLanguage("en").setRegion("US").setScript("Fooo"); + + // Will be equivalent to getScriptCode for scripts that aren't + // registered with ISO-15429 (but are otherwise well formed). + l = b.build(); + assertEquals("Fooo", l.getDisplayScript()); + } + + public void test_setLanguageTag_malformedTags() { + Locale l = fromLanguageTag("a", false); + assertEquals("und", l.getLanguage()); + assertEquals("", l.getCountry()); + assertEquals("", l.getVariant()); + assertEquals("", l.getScript()); + + l = fromLanguageTag("en-US-BA", false); + assertEquals("en", l.getLanguage()); + assertEquals("US", l.getCountry()); + assertEquals("", l.getVariant()); + assertEquals("", l.getScript()); + + l = fromLanguageTag("en-FOOOO-BA", false); + assertEquals("en", l.getLanguage()); + assertEquals("", l.getCountry()); + assertEquals("FOOOO", l.getVariant()); + assertEquals("", l.getScript()); + + l = fromLanguageTag("en-US-POSIX-P2", false); + assertEquals("en", l.getLanguage()); + assertEquals("US", l.getCountry()); + assertEquals("POSIX", l.getVariant()); + assertEquals("", l.getScript()); + + l = fromLanguageTag("en-Latn-US-P2", false); + assertEquals("en", l.getLanguage()); + assertEquals("US", l.getCountry()); + assertEquals("Latn", l.getScript()); + + l = fromLanguageTag("en-f-f", false); + assertEquals("en", l.getLanguage()); + assertEquals("", l.getCountry()); + assertEquals("", l.getVariant()); + assertEquals("", l.getScript()); + + l = fromLanguageTag("en-f", false); + assertEquals("en", l.getLanguage()); + assertEquals("", l.getCountry()); + assertEquals("", l.getVariant()); + assertEquals("", l.getScript()); + + l = fromLanguageTag("en-f-fooobaaaz", false); + assertEquals("en", l.getLanguage()); + assertEquals("", l.getCountry()); + assertEquals("", l.getVariant()); + assertEquals("", l.getScript()); + + l = fromLanguageTag("en-9-baa", false); + assertEquals("en", l.getLanguage()); + assertEquals("", l.getCountry()); + assertEquals("", l.getVariant()); + assertEquals("", l.getScript()); + } + + public void test_Builder_unicodeAttributes() { + // Adding and removing attributes + Locale.Builder b = new Locale.Builder(); + b.setLanguage("en"); + + // Well formed attribute. + b.addUnicodeLocaleAttribute("foooo"); + + try { + b.addUnicodeLocaleAttribute("fo"); + fail(); + } catch (IllformedLocaleException ifle) { + } + + try { + b.removeUnicodeLocaleAttribute("fo"); + fail(); + } catch (IllformedLocaleException ifle) { + } + + try { + b.addUnicodeLocaleAttribute("greaterthaneightchars"); + fail(); + } catch (IllformedLocaleException ifle) { + } + + try { + b.removeUnicodeLocaleAttribute("greaterthaneightchars"); + fail(); + } catch (IllformedLocaleException ifle) { + } + + try { + b.addUnicodeLocaleAttribute(null); + fail(); + } catch (NullPointerException npe) { + } + + try { + b.removeUnicodeLocaleAttribute(null); + fail(); + } catch (NullPointerException npe) { + } + + Locale l = b.build(); + assertEquals("en-u-foooo", l.toLanguageTag()); + assertTrue(l.getUnicodeLocaleAttributes().contains("foooo")); + + b.addUnicodeLocaleAttribute("dAtA"); + l = b.build(); + assertEquals("data-foooo", l.getExtension('u')); + assertTrue(l.getUnicodeLocaleAttributes().contains("data")); + assertTrue(l.getUnicodeLocaleAttributes().contains("foooo")); + } + + public void test_Builder_unicodeKeywords() { + // Adding and removing attributes + Locale.Builder b = new Locale.Builder(); + b.setLanguage("en"); + + // Key not of length 2. + try { + b.setUnicodeLocaleKeyword("k", "fooo"); + fail(); + } catch (IllformedLocaleException ifle) { + } + + // Value too short + try { + b.setUnicodeLocaleKeyword("k", "fo"); + fail(); + } catch (IllformedLocaleException ifle) { + } + + // Value too long + try { + b.setUnicodeLocaleKeyword("k", "foooooooo"); + fail(); + } catch (IllformedLocaleException ifle) { + } + + + // Null should clear the key. + b.setUnicodeLocaleKeyword("bo", "baaz"); + Locale l = b.build(); + assertEquals("bo-baaz", l.getExtension('u')); + assertEquals("baaz", l.getUnicodeLocaleType("bo")); + + b = new Locale.Builder(); + b.setUnicodeLocaleKeyword("bo", "baaz"); + b.setUnicodeLocaleKeyword("bo", null); + l = b.build(); + assertNull(l.getExtension('u')); + assertNull(l.getUnicodeLocaleType("bo")); + + // When we set attributes, they should show up before extensions. + b = new Locale.Builder(); + b.addUnicodeLocaleAttribute("fooo"); + b.addUnicodeLocaleAttribute("gooo"); + b.setUnicodeLocaleKeyword("fo", "baz"); + b.setUnicodeLocaleKeyword("ka", "kaz"); + l = b.build(); + assertEquals("fooo-gooo-fo-baz-ka-kaz", l.getExtension('u')); + assertEquals("baz", l.getUnicodeLocaleType("fo")); + assertEquals("kaz", l.getUnicodeLocaleType("ka")); + assertTrue(l.getUnicodeLocaleAttributes().contains("fooo")); + assertTrue(l.getUnicodeLocaleAttributes().contains("gooo")); + } + + public void test_multipleExtensions() { + Locale.Builder b = new Locale.Builder(); + b.setLanguage("en"); + b.addUnicodeLocaleAttribute("attrib"); + b.addUnicodeLocaleAttribute("attrib2"); + b.setExtension('f', "fo-baaz-ga-gaaz"); + b.setExtension('x', "xo-baaz-ga-gaaz"); + b.setExtension('z', "zo-baaz-ga-gaaz"); + + Locale l = b.build(); + // Implicitly added because we added unicode locale attributes. + assertEquals("attrib-attrib2", l.getExtension('u')); + assertEquals("fo-baaz-ga-gaaz", l.getExtension('f')); + assertEquals("xo-baaz-ga-gaaz", l.getExtension('x')); + assertEquals("zo-baaz-ga-gaaz", l.getExtension('z')); + } + + public void test_immutability() { + Locale.Builder b = new Locale.Builder(); + b.setExtension('g', "fooo-baaz-baar"); + b.setExtension('u', "foooo-baaar-ba-baaz-ka-kaaz"); + + Locale l = b.build(); + try { + l.getExtensionKeys().add('g'); + fail(); + } catch (UnsupportedOperationException expected) { + } + + try { + l.getUnicodeLocaleAttributes().add("fooo"); + fail(); + } catch (UnsupportedOperationException expected) { + } + } + + public void test_toLanguageTag() { + Locale.Builder b = new Locale.Builder(); + + // Empty builder. + Locale l = b.build(); + // TODO: Fix this. We should return "und" and not NULL. + // assertEquals("und", l.toLanguageTag()); + + // Only language. + b = new Locale.Builder(); + b.setLanguage("en"); + assertEquals("en", b.build().toLanguageTag()); + + // Language & Region + b = new Locale.Builder(); + b.setLanguage("en").setRegion("US"); + assertEquals("en-US", b.build().toLanguageTag()); + + // Language & Script + b = new Locale.Builder(); + b.setLanguage("en").setScript("Latn"); + assertEquals("en-Latn", b.build().toLanguageTag()); + + // Language & Variant + b = new Locale.Builder(); + b.setLanguage("en").setVariant("foooo"); + assertEquals("en-foooo", b.build().toLanguageTag()); + + // Language / script & country + b = new Locale.Builder(); + b.setLanguage("en").setScript("Latn").setRegion("US"); + assertEquals("en-Latn-US", b.build().toLanguageTag()); + + // Language / script & variant + b = new Locale.Builder(); + b.setLanguage("en").setScript("Latn").setVariant("foooo"); + assertEquals("en-Latn-foooo", b.build().toLanguageTag()); + + // Language / script / country / variant. + b = new Locale.Builder(); + b.setLanguage("en").setScript("Latn").setVariant("foooo").setRegion("US"); + assertEquals("en-Latn-US-foooo", b.build().toLanguageTag()); + + // Language / extension + b = new Locale.Builder(); + b.setLanguage("en").setExtension('x', "fooo-baar"); + assertEquals("en-x-fooo-baar", b.build().toLanguageTag()); + + // Language & multiple extensions (including unicode). + b = new Locale.Builder(); + b.setLanguage("en"); + b.addUnicodeLocaleAttribute("attrib"); + b.addUnicodeLocaleAttribute("attrib2"); + b.setExtension('f', "fo-baaz-ga-gaaz"); + b.setExtension('x', "xo-baaz-ga-gaaz"); + b.setExtension('z', "zo-baaz-ga-gaaz"); + + l = b.build(); + // Implicitly added because we added unicode locale attributes. + assertEquals("attrib-attrib2", l.getExtension('u')); + assertEquals("fo-baaz-ga-gaaz", l.getExtension('f')); + assertEquals("xo-baaz-ga-gaaz", l.getExtension('x')); + assertEquals("zo-baaz-ga-gaaz", l.getExtension('z')); + + assertEquals("en-" + + "f-fo-baaz-ga-gaaz-" + // extension tags in lexical order + "u-attrib-attrib2-z-zo-baaz-ga-gaaz-" + // unicode attribs & keywords in lex order + "x-xo-baaz-ga-gaaz", // private use extension unmodified. + l.toLanguageTag()); + } + + public void test_toString() { + Locale.Builder b = new Locale.Builder(); + + // Empty builder. + Locale l = b.build(); + assertEquals("", l.toString()); + + // Only language. + b = new Locale.Builder(); + b.setLanguage("en"); + assertEquals("en", b.build().toString()); + + // Only region + b = new Locale.Builder(); + b.setRegion("US"); + assertEquals("_US", b.build().toString()); + + // Language & Region + b = new Locale.Builder(); + b.setLanguage("en").setRegion("US"); + assertEquals("en_US", b.build().toString()); + + // Language & Script + b = new Locale.Builder(); + b.setLanguage("en").setScript("Latn"); + assertEquals("en__#Latn", b.build().toString()); + + // Language & Variant + b = new Locale.Builder(); + b.setLanguage("en").setVariant("foooo"); + assertEquals("en__foooo", b.build().toString()); + + // Language / script & country + b = new Locale.Builder(); + b.setLanguage("en").setScript("Latn").setRegion("US"); + assertEquals("en_US_#Latn", b.build().toString()); + + // Language / script & variant + b = new Locale.Builder(); + b.setLanguage("en").setScript("Latn").setVariant("foooo"); + assertEquals("en__foooo_#Latn", b.build().toString()); + + // Language / script / country / variant. + b = new Locale.Builder(); + b.setLanguage("en").setScript("Latn").setVariant("foooo").setRegion("US"); + assertEquals("en_US_foooo_#Latn", b.build().toString()); + + // Language / extension + b = new Locale.Builder(); + b.setLanguage("en").setExtension('x', "fooo-baar"); + assertEquals("en__#x-fooo-baar", b.build().toString()); + } + + // Tests cases where our "guess" for the output size is incorrect. + // + // https://b.corp.google.com/issue?id=13414549 + public void test_toLanguageTag_largerTag() { + Locale posix = new Locale.Builder() + .setLanguage("en").setRegion("US").setVariant("POSIX") + .build(); + assertEquals("en-US-POSIX", posix.toLanguageTag()); + } + + public void test_forLanguageTag_grandFatheredLocale() { + // Regular grandfathered locale. + Locale gaulish = Locale.forLanguageTag("cel-gaulish"); + assertEquals("xtg", gaulish.getLanguage()); + assertEquals("cel-gaulish", gaulish.getExtension(Locale.PRIVATE_USE_EXTENSION)); + assertEquals("", gaulish.getCountry()); + assertEquals("", gaulish.getScript()); + assertEquals("", gaulish.getVariant()); + + // Irregular grandfathered locale. + Locale enochian = Locale.forLanguageTag("i-enochian"); + assertEquals("und", enochian.getLanguage()); + assertEquals("i-enochian", enochian.getExtension(Locale.PRIVATE_USE_EXTENSION)); + assertEquals("", enochian.getCountry()); + assertEquals("", enochian.getScript()); + assertEquals("", enochian.getVariant()); + } + + // Test case from http://b/16811867 + public void testVariantsCaseSensitive() { + final Locale locale = new Locale("en", "US", "variant"); + assertEquals("variant", locale.getVariant()); + assertEquals(locale, Locale.forLanguageTag(locale.toLanguageTag())); } - } +} diff --git a/luni/src/test/java/libcore/java/util/OldAndroidLocaleTest.java b/luni/src/test/java/libcore/java/util/OldAndroidLocaleTest.java index fa761d3..87f2f9d 100644 --- a/luni/src/test/java/libcore/java/util/OldAndroidLocaleTest.java +++ b/luni/src/test/java/libcore/java/util/OldAndroidLocaleTest.java @@ -76,9 +76,16 @@ public class OldAndroidLocaleTest extends TestCase { // This one makes sure we have all necessary locales installed. public void testICULocales() { - String[] locales = new String[] { - // List of locales currently required for Android. - "en_US", "es_US", "en_GB", "fr_FR", "de_DE", "de_AT", "cs_CZ", "nl_NL" }; + // List of locales currently required for Android. + Locale[] locales = new Locale[] { + new Locale("en", "US"), + new Locale("es", "US"), + new Locale("en", "GB"), + new Locale("fr", "FR"), + new Locale("de", "DE"), + new Locale("de", "AT"), + new Locale("cs", "CZ"), + new Locale("nl", "NL") }; String[] mondays = new String[] { "Monday", "lunes", "Monday", "lundi", "Montag", "Montag", "pond\u011bl\u00ed", "maandag" }; @@ -87,14 +94,12 @@ public class OldAndroidLocaleTest extends TestCase { "USD", "USD", "GBP", "EUR", "EUR", "EUR", "CZK", "EUR"}; for (int i = 0; i < locales.length; i++) { - Locale l = new Locale(locales[i].substring(0, 2), locales[i].substring(3)); + final Locale l = locales[i]; - // Check language part of locale. DateFormatSymbols d = new DateFormatSymbols(l); assertEquals("Monday name for " + locales[i] + " must match", mondays[i], d.getWeekdays()[2]); - // Check country part of locale. Currency c = Currency.getInstance(l); assertEquals("Currency code for " + locales[i] + " must match", currencies[i], c.getCurrencyCode()); diff --git a/luni/src/test/java/libcore/java/util/OldTimeZoneTest.java b/luni/src/test/java/libcore/java/util/OldTimeZoneTest.java index 713e1b5..ecf2e5f 100644 --- a/luni/src/test/java/libcore/java/util/OldTimeZoneTest.java +++ b/luni/src/test/java/libcore/java/util/OldTimeZoneTest.java @@ -25,7 +25,7 @@ import junit.framework.TestCase; public class OldTimeZoneTest extends TestCase { - class Mock_TimeZone extends TimeZone { + static class Mock_TimeZone extends TimeZone { @Override public int getOffset(int era, int year, int month, int day, int dayOfWeek, int milliseconds) { return 0; @@ -91,29 +91,50 @@ public class OldTimeZoneTest extends TestCase { public void test_getDisplayNameLjava_util_Locale() { TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles"); - assertEquals("Pacific Standard Time", tz.getDisplayName(new Locale("US"))); - assertEquals("heure normale du Pacifique", tz.getDisplayName(Locale.FRANCE)); + assertEquals("Pacific Standard Time", tz.getDisplayName(Locale.US)); + assertEquals("heure normale du Pacifique nord-américain", tz.getDisplayName(Locale.FRANCE)); } public void test_getDisplayNameZI() { Locale.setDefault(Locale.US); TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles"); - assertEquals("PST", tz.getDisplayName(false, 0)); - assertEquals("Pacific Daylight Time", tz.getDisplayName(true, 1)); - assertEquals("Pacific Standard Time", tz.getDisplayName(false, 1)); + assertEquals("PST", tz.getDisplayName(false, TimeZone.SHORT)); + assertEquals("Pacific Daylight Time", tz.getDisplayName(true, TimeZone.LONG)); + assertEquals("Pacific Standard Time", tz.getDisplayName(false, TimeZone.LONG)); } @AndroidOnly("fail on RI. See comment below") public void test_getDisplayNameZILjava_util_Locale() { TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles"); - assertEquals("PST", tz.getDisplayName(false, 0, Locale.US)); - assertEquals("Pacific Daylight Time", tz.getDisplayName(true, 1, Locale.US)); - assertEquals("Pacific Standard Time", tz.getDisplayName(false, 1, Locale.UK)); - // RI always returns short time zone name as "PST" - // ICU zone/root.txt patched to allow metazone names. - assertEquals("PST", tz.getDisplayName(false, 0, Locale.FRANCE)); - assertEquals("heure avanc\u00e9e du Pacifique", tz.getDisplayName(true, 1, Locale.FRANCE)); - assertEquals("heure normale du Pacifique", tz.getDisplayName(false, 1, Locale.FRANCE)); + assertEquals("Pacific Daylight Time", tz.getDisplayName(true, TimeZone.LONG, Locale.US)); + assertEquals("Pacific Standard Time", tz.getDisplayName(false, TimeZone.LONG, Locale.UK)); + assertEquals("heure avanc\u00e9e du Pacifique", + tz.getDisplayName(true, TimeZone.LONG, Locale.FRANCE)); + assertEquals("heure normale du Pacifique nord-américain", + tz.getDisplayName(false, TimeZone.LONG, Locale.FRANCE)); + + assertEquals("PDT", tz.getDisplayName(true, TimeZone.SHORT, Locale.US)); + assertEquals("PST", tz.getDisplayName(false, TimeZone.SHORT, Locale.US)); + // RI fails on following lines. RI always returns short time zone name for + // "America/Los_Angeles" as "PST", Android only returns a string if ICU has a translation. + // There is no short time zone name for America/Los_Angeles in French or British English in + // ICU data so an offset is returned instead. + assertEquals("GMT-08:00", tz.getDisplayName(false, TimeZone.SHORT, Locale.FRANCE)); + assertEquals("GMT-07:00", tz.getDisplayName(true, TimeZone.SHORT, Locale.FRANCE)); + assertEquals("GMT-08:00", tz.getDisplayName(false, TimeZone.SHORT, Locale.UK)); + assertEquals("GMT-07:00", tz.getDisplayName(true, TimeZone.SHORT, Locale.UK)); + + // The RI behavior mentioned above does not appear to be because "PST" is a legacy + // three-character timezone supported by the RI: it happens for "Asia/Tehran"/"IRST" too + // (IRST is not a legacy code). The RI may just use a different dataset that has "PST" / + // "IRST" as valid translations (even for scripts like Chinese). + TimeZone iranTz = TimeZone.getTimeZone("Asia/Tehran"); + assertEquals("Iran Summer Time", iranTz.getDisplayName(true, TimeZone.LONG, Locale.UK)); + assertEquals("Iran Daylight Time", iranTz.getDisplayName(true, TimeZone.LONG, Locale.US)); + assertEquals("Iran Standard Time", iranTz.getDisplayName(false, TimeZone.LONG, Locale.UK)); + assertEquals("Iran Standard Time", iranTz.getDisplayName(false, TimeZone.LONG, Locale.US)); + assertEquals("GMT+03:30", iranTz.getDisplayName(false, TimeZone.SHORT, Locale.UK)); + assertEquals("GMT+04:30", iranTz.getDisplayName(true, TimeZone.SHORT, Locale.UK)); } public void test_getID() { diff --git a/luni/src/test/java/libcore/java/util/ResourceLeakageDetector.java b/luni/src/test/java/libcore/java/util/ResourceLeakageDetector.java new file mode 100644 index 0000000..954665a --- /dev/null +++ b/luni/src/test/java/libcore/java/util/ResourceLeakageDetector.java @@ -0,0 +1,90 @@ +/* + * Copyright (C) 2014 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.util; + +/** + * Detects resource leakages for resources that are protected by <code>CloseGuard</code> mechanism. + * + * <p>If multiple instances of this are active at the same time, i.e. have been created but not yet + * had their {@link #checkForLeaks()} method called then while they will report all the leakages + * detected they may report the leakages caused by the code being tested by another detector. + * + * <p>The underlying CloseGuardMonitor is loaded using reflection to ensure that this will run, + * albeit doing nothing, on the reference implementation. + */ +public class ResourceLeakageDetector { + /** The class for the CloseGuardMonitor, null if not supported. */ + private static final Class<?> CLOSE_GUARD_MONITOR_CLASS; + + static { + ClassLoader classLoader = ResourceLeakageDetector.class.getClassLoader(); + Class<?> clazz; + try { + // Make sure that the CloseGuard class exists; this ensures that this is not running + // on a RI JVM. + classLoader.loadClass("dalvik.system.CloseGuard"); + + // Load the monitor class for later instantiation. + clazz = classLoader.loadClass("dalvik.system.CloseGuardMonitor"); + + } catch (ClassNotFoundException e) { + System.err.println("Resource leakage will not be detected; " + + "this is expected in the reference implementation"); + e.printStackTrace(System.err); + + // Ignore, probably running in reference implementation. + clazz = null; + } + + CLOSE_GUARD_MONITOR_CLASS = clazz; + } + + /** + * The underlying CloseGuardMonitor that will perform the post test checks for resource + * leakage. + */ + private Runnable postTestChecker; + + /** + * Create a new detector. + * + * @return The new {@link ResourceLeakageDetector}, its {@link #checkForLeaks()} method must be + * called otherwise it will not clean up properly after itself. + */ + public static ResourceLeakageDetector newDetector() + throws Exception { + return new ResourceLeakageDetector(); + } + + private ResourceLeakageDetector() + throws Exception { + if (CLOSE_GUARD_MONITOR_CLASS != null) { + postTestChecker = (Runnable) CLOSE_GUARD_MONITOR_CLASS.newInstance(); + } + } + + /** + * Detect any leaks that have arisen since this was created. + * + * @throws Exception If any leaks were detected. + */ + public void checkForLeaks() throws Exception { + // If available check for resource leakage. + if (postTestChecker != null) { + postTestChecker.run(); + } + } +} diff --git a/luni/src/test/java/libcore/java/util/ResourceLeakageDetectorTest.java b/luni/src/test/java/libcore/java/util/ResourceLeakageDetectorTest.java new file mode 100644 index 0000000..d86c9f2 --- /dev/null +++ b/luni/src/test/java/libcore/java/util/ResourceLeakageDetectorTest.java @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2014 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.util; + +import dalvik.system.CloseGuard; +import junit.framework.TestCase; + +/** + * Test for {@link ResourceLeakageDetector} + */ +public class ResourceLeakageDetectorTest extends TestCase { + /** + * This test will not work on RI as it does not support the <code>CloseGuard</code> or similar + * mechanism. + */ + public void testDetectsUnclosedCloseGuard() throws Exception { + ResourceLeakageDetector detector = ResourceLeakageDetector.newDetector(); + try { + CloseGuard closeGuard = createCloseGuard(); + closeGuard.open("open"); + } finally { + try { + System.logI("Checking for leaks"); + detector.checkForLeaks(); + fail(); + } catch (AssertionError expected) { + } + } + } + + public void testIgnoresClosedCloseGuard() throws Exception { + ResourceLeakageDetector detector = ResourceLeakageDetector.newDetector(); + try { + CloseGuard closeGuard = createCloseGuard(); + closeGuard.open("open"); + closeGuard.close(); + } finally { + detector.checkForLeaks(); + } + } + + /** + * Private method to ensure that the CloseGuard object is garbage collected. + */ + private CloseGuard createCloseGuard() { + final CloseGuard closeGuard = CloseGuard.get(); + new Object() { + @Override + protected void finalize() throws Throwable { + try { + closeGuard.warnIfOpen(); + } finally { + super.finalize(); + } + } + }; + + return closeGuard; + } +} diff --git a/luni/src/test/java/libcore/java/util/TimeZoneTest.java b/luni/src/test/java/libcore/java/util/TimeZoneTest.java index 08d1e69..0bc02b0 100644 --- a/luni/src/test/java/libcore/java/util/TimeZoneTest.java +++ b/luni/src/test/java/libcore/java/util/TimeZoneTest.java @@ -57,6 +57,7 @@ public class TimeZoneTest extends TestCase { // http://code.google.com/p/android/issues/detail?id=14395 public void testPreHistoricInDaylightTime() throws Exception { + Locale.setDefault(Locale.US); TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles"); TimeZone.setDefault(tz); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); @@ -275,14 +276,6 @@ public class TimeZoneTest extends TestCase { assertEquals("", failures.toString()); } - public void testSantiago() throws Exception { - TimeZone tz = TimeZone.getTimeZone("America/Santiago"); - assertEquals("Chile Summer Time", tz.getDisplayName(true, TimeZone.LONG, Locale.US)); - assertEquals("Chile Standard Time", tz.getDisplayName(false, TimeZone.LONG, Locale.US)); - assertEquals("GMT-03:00", tz.getDisplayName(true, TimeZone.SHORT, Locale.US)); - assertEquals("GMT-04:00", tz.getDisplayName(false, TimeZone.SHORT, Locale.US)); - } - // http://b/7955614 public void testApia() throws Exception { TimeZone tz = TimeZone.getTimeZone("Pacific/Apia"); diff --git a/luni/src/test/java/libcore/java/util/UUIDTest.java b/luni/src/test/java/libcore/java/util/UUIDTest.java new file mode 100644 index 0000000..61e4ae0 --- /dev/null +++ b/luni/src/test/java/libcore/java/util/UUIDTest.java @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2014 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.util; + +import java.util.UUID; +import junit.framework.TestCase; + +// There are more tests in the harmony suite: +// harmony-tests/src/test/java/org/apache/harmony/tests/java/util/UUIDTest.java +public class UUIDTest extends TestCase { + + public void testFromStringInvalidValues() { + try { + UUID.fromString("+f81d4fae-7dec-11d0-a765-00a0c91e6bf6"); + fail(); + } catch (IllegalArgumentException expected) { } + + try { + UUID.fromString("f81d4fae-+7dec-11d0-a765-00a0c91e6bf6"); + fail(); + } catch (IllegalArgumentException expected) { } + + try { + UUID.fromString("f81d4fae-7dec-+11d0-a765-00a0c91e6bf6"); + fail(); + } catch (IllegalArgumentException expected) { } + + try { + UUID.fromString("f81d4fae-7dec-11d0-+a765-00a0c91e6bf6"); + fail(); + } catch (IllegalArgumentException expected) { } + + try { + UUID.fromString("f81d4fae-7dec-11d0-a765-+00a0c91e6bf6"); + fail(); + } catch (IllegalArgumentException expected) { } + } + +} diff --git a/luni/src/test/java/libcore/java/util/jar/DalvikExecTest.java b/luni/src/test/java/libcore/java/util/jar/DalvikExecTest.java deleted file mode 100644 index 021cd3f..0000000 --- a/luni/src/test/java/libcore/java/util/jar/DalvikExecTest.java +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Copyright (C) 2008 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.util.jar; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.jar.Attributes; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.jar.JarOutputStream; -import java.util.jar.Manifest; -import junit.framework.TestCase; -import libcore.io.Streams; -import static tests.support.Support_Exec.execAndGetOutput; -import tests.support.resource.Support_Resources; - - -public class DalvikExecTest extends TestCase { - - String execDalvik1(String classpath, String mainClass, String arg1) - throws IOException, InterruptedException { - ProcessBuilder builder = new ProcessBuilder(); - - File dalvikvm = new File("/system/bin/dalvikvm"); - if (dalvikvm.exists()) { - builder.command().add(dalvikvm.getPath()); - } else { - builder.command().add("dalvikvm"); // for host mode, assume dalvikvm is on the path - } - - builder.command().add("-Duser.language=en"); - builder.command().add("-Duser.region=US"); - builder.command().add("-Xbootclasspath:" + System.getProperty("java.boot.class.path")); - builder.command().add("-classpath"); - builder.command().add(classpath); - builder.command().add(mainClass); - - if (arg1 != null) { - builder.command().add(arg1); - } - - // Create a writable dalvik-cache under ANDROID_DATA. - // The default dalvik-cache is only writable by the system user (and root). - String tmp = System.getProperty("java.io.tmpdir"); - builder.environment().put("ANDROID_DATA", tmp); - new File(tmp, "dalvik-cache").mkdir(); - - return execAndGetOutput(builder); - } - - String execDalvik (String classpath, String mainClass) - throws IOException, InterruptedException { - return execDalvik1(classpath, mainClass, null); - } - - // Execute an existing JAR on dalvikvm using -classpath option.", - public void test_execExistingJar () throws IOException, InterruptedException { - String res; - File jarFile; - if (System.getProperty("java.vendor").contains("Android")) { - // - // Test against Android: - // - File tempDir = Support_Resources.createTempFolder(); - jarFile = Support_Resources.copyFile( - tempDir, null, "cts_dalvikExecTest.jar" ); - res = execDalvik(jarFile.getAbsolutePath(), "dalvikExecTest.HelloWorld"); - assertEquals("Hello Android World!", "Hello Android World!\n", res); - - res = execDalvik(jarFile.getAbsolutePath(), "dalvikExecTest.ResourceDumper"); - assertTrue("Android Resource Dumper started", - res.contains("Android Resource Dumper started")); - assertTrue("This Resource contains some text.", - res.contains("This Resource contains some text.")); - } else { - // - // Test against RI: - // - // Do nothing! - } - } - - // Create a temp file, fill it with contents according to Dalvik JAR format, and execute it on dalvikvm using -classpath option.", - public void test_execCreatedJar () throws IOException, InterruptedException { - File jarFile = File.createTempFile("cts_dalvikExecTest_", ".jar"); - jarFile.deleteOnExit(); - - // Create a JAR output stream on the temp file: - JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(jarFile)); - - // Define the entry for the classes.dex: - jarOut.putNextEntry(new JarEntry("classes.dex")); - - // Fill in the classes.dex contents, i.e. the Dalvik executable code: - // (See below for the detailed source code contents.) - Streams.copy(Support_Resources.getResourceStream("cts_dalvikExecTest_classes.dex"), jarOut); - - // Now add a resource file: - // - jarOut.putNextEntry(new JarEntry("dalvikExecTest/myResource")); - jarOut.write("This Resource contains some text.".getBytes()); - - // Close the stream to the completed JAR file. - jarOut.close(); - - // The resulting JAR file contains the classes listed at the end of this text, - // like the 'cts_dalvikExecTest.jar' as part of the resources, too. - - String res; - - res = execDalvik(jarFile.getAbsolutePath(), "dalvikExecTest.HelloWorld"); - assertEquals("Hello Android World!", "Hello Android World!\n", res); - - res = execDalvik(jarFile.getAbsolutePath(), "dalvikExecTest.ResourceDumper"); - assertTrue("Android Resource Dumper started", - res.contains("Android Resource Dumper started")); - assertTrue("This Resource contains some text.", - res.contains("This Resource contains some text.")); - } - - - /** - * This test does quite the same as test_execCreatedJar, but includes a manifest. - * Note however that the Dalvik JAR format does not require this manifest. - * We just test whether the manifest is placed correctly within the JAR by - * dumping its contents read as a simple text resource. - * No! We can't do that so easily either, as there are other (parent) JARs - * with a manifest inside, taken with precedence. - * So we will reopen the JAR as a JarFile and check the manifest - * with a top level end-to-end approach. - */ - public void test_execCreatedJarWithManifest () throws IOException, InterruptedException { - File jarFile = File.createTempFile("cts_dalvikExecTest_", ".jar"); - jarFile.deleteOnExit(); - - // Create the manifest: - Manifest manifest = new Manifest(); - Attributes attrs = manifest.getMainAttributes(); - attrs.put(Attributes.Name.MANIFEST_VERSION, "3.1415962"); - attrs.put(Attributes.Name.MAIN_CLASS, "dalvikExecTest.HelloWorld"); - attrs.put(Attributes.Name.CLASS_PATH, jarFile.getName()); - - // Create a JAR output stream on the temp file using the manifest: - JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(jarFile), manifest); - - // Define the entry for the classes.dex: - jarOut.putNextEntry(new JarEntry("classes.dex")); - - // Fill in the classes.dex contents, i.e. the Dalvik executable code: - // (See below for the detailed source code contents.) - Streams.copy(Support_Resources.getResourceStream("cts_dalvikExecTest_classes.dex"), jarOut); - - // Now add a resource file: - // - jarOut.putNextEntry(new JarEntry("dalvikExecTest/myResource")); - jarOut.write("This Resource contains some text.".getBytes()); - - // Close the stream to the completed JAR file. - jarOut.close(); - - // The resulting JAR file contains the classes listed at the end of this text, - // like the 'cts_dalvikExecTest.jar' as part of the resources, too. - - String res; - - res = execDalvik(jarFile.getAbsolutePath(), "dalvikExecTest.HelloWorld"); - assertEquals("Hello Android World!", "Hello Android World!\n", res); - - res = execDalvik(jarFile.getAbsolutePath(), "dalvikExecTest.ResourceDumper"); - assertTrue("Android Resource Dumper started", - res.contains("Android Resource Dumper started")); - assertTrue("This Resource contains some text.", - res.contains("This Resource contains some text.")); - - // And now reread the manifest: - // - JarFile jarIn = new JarFile(jarFile); - manifest = jarIn.getManifest(); - attrs = manifest.getMainAttributes(); - assertEquals("MANIFEST_VERSION must match!", "3.1415962", - attrs.get(Attributes.Name.MANIFEST_VERSION)); - assertEquals("MAIN_CLASS must match!", "dalvikExecTest.HelloWorld", - attrs.get(Attributes.Name.MAIN_CLASS)); - assertEquals("CLASS_PATH must match!", jarFile.getName(), - attrs.get(Attributes.Name.CLASS_PATH)); - } - - - /* - * The following two classes are added, here, only for completeness. - * They form the contents of the dalvikExecTest package contained - * in the 'cts_dalvikExecTest_classes.dex' resource file. - */ - /** - * @hide - */ - public static class HelloWorld { - - public static void main(String[] args) { - System.out.println("Hello Android World!"); - } - - } - - public static class ResourceDumper { - - static ByteArrayOutputStream outputFrom (InputStream input) throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - byte[] buffer = new byte[512]; - int total = 0; - int count; - count = input.read(buffer); - while (count != -1) { - out.write(buffer, 0, count); - total = total + count; - count = input.read(buffer); - } - return out; - } - - public static void main(String[] args) throws IOException { - System.out.print("Android Resource Dumper started "); - String fileName; - if (args.length >= 1) { - fileName = args[0]; - System.out.format("for argument '%s'.\n", fileName); - } else { - System.out.print("standard "); - fileName = "myResource"; - System.out.println("for standard 'myResource'."); - } - InputStream is = ResourceDumper.class.getResourceAsStream(fileName); - if (is != null) { - System.out.println("Resource obtained and being dumped:"); - System.out.println(outputFrom(is).toString()); - } - } - - } - -} diff --git a/luni/src/test/java/libcore/java/util/jar/StrictJarFileTest.java b/luni/src/test/java/libcore/java/util/jar/StrictJarFileTest.java new file mode 100644 index 0000000..e5a6cd8 --- /dev/null +++ b/luni/src/test/java/libcore/java/util/jar/StrictJarFileTest.java @@ -0,0 +1,181 @@ +/* + * Copyright (C) 2013 Google Inc. + * + * 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.util.jar; + +import junit.framework.TestCase; +import tests.support.resource.Support_Resources; +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.Iterator; +import java.util.jar.StrictJarFile; +import java.util.zip.ZipEntry; +import libcore.io.Streams; + +public class StrictJarFileTest extends TestCase { + + // A well formed jar file with 6 entries. + private static final String JAR_1 = "hyts_patch.jar"; + + private File resources; + + @Override + protected void setUp() { + resources = Support_Resources.createTempFolder(); + } + + public void testConstructor() throws Exception { + try { + StrictJarFile jarFile = new StrictJarFile("Wrong.file"); + fail("Should throw IOException"); + } catch (IOException e) { + // expected + } + + Support_Resources.copyFile(resources, null, JAR_1); + String fileName = (new File(resources, JAR_1)).getCanonicalPath(); + StrictJarFile jarFile = new StrictJarFile(fileName); + jarFile.close(); + } + + public void testIteration() throws Exception { + Support_Resources.copyFile(resources, null, JAR_1); + StrictJarFile jarFile = new StrictJarFile(new File(resources, JAR_1).getAbsolutePath()); + + Iterator<ZipEntry> it = jarFile.iterator(); + HashMap<String, ZipEntry> entries = new HashMap<String, ZipEntry>(); + while (it.hasNext()) { + final ZipEntry ze = it.next(); + entries.put(ze.getName(), ze); + } + + assertEquals(6, entries.size()); + assertTrue(entries.containsKey("META-INF/")); + + assertTrue(entries.containsKey("META-INF/MANIFEST.MF")); + ZipEntry ze = entries.get("META-INF/MANIFEST.MF"); + assertEquals(62, ze.getSize()); + assertEquals(ZipEntry.DEFLATED, ze.getMethod()); + assertEquals(61, ze.getCompressedSize()); + + assertTrue(entries.containsKey("Blah.txt")); + ze = entries.get("Blah.txt"); + assertEquals(4, ze.getSize()); + assertEquals(ZipEntry.DEFLATED, ze.getMethod()); + assertEquals(6, ze.getCompressedSize()); + assertEquals("Blah", new String(Streams.readFully(jarFile.getInputStream(ze)), + Charset.forName("UTF-8"))); + + assertTrue(entries.containsKey("foo/")); + assertTrue(entries.containsKey("foo/bar/")); + assertTrue(entries.containsKey("foo/bar/A.class")); + ze = entries.get("foo/bar/A.class"); + assertEquals(311, ze.getSize()); + assertEquals(ZipEntry.DEFLATED, ze.getMethod()); + assertEquals(225, ze.getCompressedSize()); + } + + public void testFindEntry() throws Exception { + Support_Resources.copyFile(resources, null, JAR_1); + StrictJarFile jarFile = new StrictJarFile(new File(resources, JAR_1).getAbsolutePath()); + + assertNull(jarFile.findEntry("foobar")); + assertNull(jarFile.findEntry("blah.txt")); + assertNotNull(jarFile.findEntry("Blah.txt")); + final ZipEntry ze = jarFile.findEntry("Blah.txt"); + assertEquals(4, ze.getSize()); + assertEquals(ZipEntry.DEFLATED, ze.getMethod()); + assertEquals(6, ze.getCompressedSize()); + assertEquals("Blah", new String(Streams.readFully(jarFile.getInputStream(ze)), + Charset.forName("UTF-8"))); + } + + public void testGetManifest() throws Exception { + Support_Resources.copyFile(resources, null, JAR_1); + StrictJarFile jarFile = new StrictJarFile(new File(resources, JAR_1).getAbsolutePath()); + + assertNotNull(jarFile.getManifest()); + assertEquals("1.4.2 (IBM Corporation)", jarFile.getManifest().getMainAttributes().getValue("Created-By")); + } + + public void testJarSigning_wellFormed() throws IOException { + Support_Resources.copyFile(resources, null, "Integrate.jar"); + StrictJarFile jarFile = new StrictJarFile(new File(resources, "Integrate.jar").getAbsolutePath()); + Iterator<ZipEntry> entries = jarFile.iterator(); + while (entries.hasNext()) { + ZipEntry zipEntry = entries.next(); + jarFile.getInputStream(zipEntry).skip(Long.MAX_VALUE); + if ("Test.class".equals(zipEntry.getName())) { + assertNotNull(jarFile.getCertificates(zipEntry)); + assertNotNull(jarFile.getCertificateChains(zipEntry)); + } + } + } + + public void testJarSigning_fudgedEntry() throws IOException { + Support_Resources.copyFile(resources, null, "Integrate.jar"); + StrictJarFile jarFile = new StrictJarFile( + new File(resources, "Integrate.jar").getAbsolutePath()); + + ZipEntry ze = jarFile.findEntry("Test.class"); + jarFile.getInputStream(ze).skip(Long.MAX_VALUE); + + // Fudge the size so that certificates do not match. + ze.setSize(ze.getSize() - 1); + try { + jarFile.getInputStream(ze).skip(Long.MAX_VALUE); + fail(); + } catch (SecurityException expected) { + } + } + + public void testJarSigning_modifiedClass() throws IOException { + Support_Resources.copyFile(resources, null, "Modified_Class.jar"); + StrictJarFile jarFile = new StrictJarFile( + new File(resources, "Modified_Class.jar").getAbsolutePath()); + + ZipEntry ze = jarFile.findEntry("Test.class"); + try { + jarFile.getInputStream(ze).skip(Long.MAX_VALUE); + fail(); + } catch (SecurityException expected) { + } + } + + public void testJarSigning_brokenMainAttributes() throws Exception { + assertThrowsOnInit("Modified_Manifest_MainAttributes.jar"); + } + + public void testJarSigning_brokenEntryAttributes() throws Exception { + assertThrowsOnInit("Modified_Manifest_EntryAttributes.jar"); + } + + public void testJarSigning_brokenSignatureFile() throws Exception { + assertThrowsOnInit("Modified_SF_EntryAttributes.jar"); + } + + private void assertThrowsOnInit(String name) throws Exception { + Support_Resources.copyFile(resources, null, name); + try { + StrictJarFile jarFile = new StrictJarFile( + new File(resources, name).getAbsolutePath()); + fail(); + } catch (SecurityException expected) { + } + } +} diff --git a/luni/src/test/java/libcore/java/util/prefs/OldAbstractPreferencesTest.java b/luni/src/test/java/libcore/java/util/prefs/OldAbstractPreferencesTest.java index b9d3f1d..693f0c2 100644 --- a/luni/src/test/java/libcore/java/util/prefs/OldAbstractPreferencesTest.java +++ b/luni/src/test/java/libcore/java/util/prefs/OldAbstractPreferencesTest.java @@ -18,6 +18,7 @@ package libcore.java.util.prefs; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.File; import java.io.IOException; import java.util.prefs.AbstractPreferences; import java.util.prefs.BackingStoreException; @@ -27,12 +28,17 @@ import java.util.prefs.NodeChangeListener; import java.util.prefs.PreferenceChangeEvent; import java.util.prefs.PreferenceChangeListener; import java.util.prefs.Preferences; +import java.util.prefs.PreferencesFactory; + import junit.framework.TestCase; +import libcore.io.IoUtils; public final class OldAbstractPreferencesTest extends TestCase { static final String nodeName = "mock"; + private PreferencesFactory defaultFactory; + AbstractPreferences pref; AbstractPreferences root; AbstractPreferences parent = null; @@ -40,16 +46,24 @@ public final class OldAbstractPreferencesTest extends TestCase { protected void setUp() throws Exception { super.setUp(); + File tmpDir = IoUtils.createTemporaryDirectory("OldAbstractPreferencesTest"); + defaultFactory = Preferences.setPreferencesFactory( + new PreferencesTest.TestPreferencesFactory(tmpDir.getAbsolutePath())); + root = (AbstractPreferences) Preferences.userRoot(); - for (String child : root.childrenNames()) { - root.node(child).removeNode(); - } - root.clear(); + assertEquals(0, root.childrenNames().length); + assertEquals(0, root.keys().length); parent = (AbstractPreferences) Preferences.userNodeForPackage(getClass()); pref = (AbstractPreferences) parent.node(nodeName); } + @Override + public void tearDown() throws Exception { + Preferences.setPreferencesFactory(defaultFactory); + super.tearDown(); + } + public void testToString() { assertTrue(pref.toString().contains(nodeName)); } diff --git a/luni/src/test/java/libcore/java/util/prefs/OldFilePreferencesImplTest.java b/luni/src/test/java/libcore/java/util/prefs/OldFilePreferencesImplTest.java index 93ba485..ea8cb39 100644 --- a/luni/src/test/java/libcore/java/util/prefs/OldFilePreferencesImplTest.java +++ b/luni/src/test/java/libcore/java/util/prefs/OldFilePreferencesImplTest.java @@ -16,11 +16,32 @@ package libcore.java.util.prefs; +import java.io.File; import java.util.prefs.Preferences; +import java.util.prefs.PreferencesFactory; + import junit.framework.TestCase; +import libcore.io.IoUtils; + public final class OldFilePreferencesImplTest extends TestCase { + private PreferencesFactory defaultFactory; + + @Override + public void setUp() throws Exception { + super.setUp(); + File tmpDir = IoUtils.createTemporaryDirectory("OldFilePreferencesImplTest"); + defaultFactory = Preferences.setPreferencesFactory( + new PreferencesTest.TestPreferencesFactory(tmpDir.getAbsolutePath())); + } + + @Override + public void tearDown() throws Exception { + Preferences.setPreferencesFactory(defaultFactory); + super.tearDown(); + } + // AndroidOnly: the RI can't remove nodes created in the system root. public void testSystemChildNodes() throws Exception { Preferences sroot = Preferences.systemRoot().node("test"); diff --git a/luni/src/test/java/libcore/java/util/prefs/OldNodeChangeEventTest.java b/luni/src/test/java/libcore/java/util/prefs/OldNodeChangeEventTest.java index f2d483e..7ba1dfe 100644 --- a/luni/src/test/java/libcore/java/util/prefs/OldNodeChangeEventTest.java +++ b/luni/src/test/java/libcore/java/util/prefs/OldNodeChangeEventTest.java @@ -16,15 +16,36 @@ package libcore.java.util.prefs; +import java.io.File; import java.util.prefs.AbstractPreferences; import java.util.prefs.BackingStoreException; import java.util.prefs.NodeChangeEvent; import java.util.prefs.NodeChangeListener; import java.util.prefs.Preferences; +import java.util.prefs.PreferencesFactory; + import junit.framework.TestCase; +import libcore.io.IoUtils; + public final class OldNodeChangeEventTest extends TestCase { + private PreferencesFactory defaultFactory; + + @Override + public void setUp() throws Exception { + super.setUp(); + File tmpDir = IoUtils.createTemporaryDirectory("OldNodeChangeEventTest"); + defaultFactory = Preferences.setPreferencesFactory( + new PreferencesTest.TestPreferencesFactory(tmpDir.getAbsolutePath())); + } + + @Override + public void tearDown() throws Exception { + Preferences.setPreferencesFactory(defaultFactory); + super.tearDown(); + } + public void testGetChild() throws BackingStoreException { AbstractPreferences parent = (AbstractPreferences) Preferences .userNodeForPackage(Preferences.class); diff --git a/luni/src/test/java/libcore/java/util/prefs/OldPreferenceChangeEventTest.java b/luni/src/test/java/libcore/java/util/prefs/OldPreferenceChangeEventTest.java index acdbd69..d77a11c 100644 --- a/luni/src/test/java/libcore/java/util/prefs/OldPreferenceChangeEventTest.java +++ b/luni/src/test/java/libcore/java/util/prefs/OldPreferenceChangeEventTest.java @@ -16,14 +16,35 @@ package libcore.java.util.prefs; +import java.io.File; import java.util.prefs.AbstractPreferences; import java.util.prefs.PreferenceChangeEvent; import java.util.prefs.PreferenceChangeListener; import java.util.prefs.Preferences; +import java.util.prefs.PreferencesFactory; + import junit.framework.TestCase; +import libcore.io.IoUtils; + public final class OldPreferenceChangeEventTest extends TestCase { + private PreferencesFactory defaultFactory; + + @Override + public void setUp() throws Exception { + super.setUp(); + File tmpDir = IoUtils.createTemporaryDirectory("OldPreferenceChangeEventTest"); + defaultFactory = Preferences.setPreferencesFactory( + new PreferencesTest.TestPreferencesFactory(tmpDir.getAbsolutePath())); + } + + @Override + public void tearDown() throws Exception { + Preferences.setPreferencesFactory(defaultFactory); + super.tearDown(); + } + public void testGetKey() { AbstractPreferences parent = (AbstractPreferences) Preferences .userNodeForPackage(Preferences.class); diff --git a/luni/src/test/java/libcore/java/util/prefs/OldPreferencesTest.java b/luni/src/test/java/libcore/java/util/prefs/OldPreferencesTest.java index f8a8154..7245af7 100644 --- a/luni/src/test/java/libcore/java/util/prefs/OldPreferencesTest.java +++ b/luni/src/test/java/libcore/java/util/prefs/OldPreferencesTest.java @@ -16,6 +16,7 @@ package libcore.java.util.prefs; +import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; @@ -25,7 +26,9 @@ import java.util.prefs.NodeChangeListener; import java.util.prefs.PreferenceChangeEvent; import java.util.prefs.PreferenceChangeListener; import java.util.prefs.Preferences; +import java.util.prefs.PreferencesFactory; import junit.framework.TestCase; +import libcore.io.IoUtils; public final class OldPreferencesTest extends TestCase { @@ -48,8 +51,14 @@ public final class OldPreferencesTest extends TestCase { longValue = value.toString(); } - @Override protected void setUp() throws Exception { + private PreferencesFactory defaultFactory; + + @Override + protected void setUp() throws Exception { super.setUp(); + final File tmpDir = IoUtils.createTemporaryDirectory("OldPreferenceTest"); + defaultFactory = Preferences.setPreferencesFactory( + new PreferencesTest.TestPreferencesFactory(tmpDir.getAbsolutePath())); Preferences pref = Preferences.userNodeForPackage(Preferences.class); for (String child : pref.childrenNames()) { @@ -58,6 +67,11 @@ public final class OldPreferencesTest extends TestCase { pref.clear(); } + @Override + protected void tearDown() throws Exception { + Preferences.setPreferencesFactory(defaultFactory); + } + public void testAbstractMethods() throws IOException, BackingStoreException { Preferences p = new MockPreferences(); p.absolutePath(); diff --git a/luni/src/test/java/libcore/java/util/prefs/PreferencesTest.java b/luni/src/test/java/libcore/java/util/prefs/PreferencesTest.java index 1560fbe..6c57ef9 100644 --- a/luni/src/test/java/libcore/java/util/prefs/PreferencesTest.java +++ b/luni/src/test/java/libcore/java/util/prefs/PreferencesTest.java @@ -19,17 +19,58 @@ package libcore.java.util.prefs; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileWriter; +import java.util.prefs.FilePreferencesImpl; import java.util.prefs.Preferences; +import java.util.prefs.PreferencesFactory; import junit.framework.TestCase; +import libcore.io.IoUtils; public final class PreferencesTest extends TestCase { /** + * A preferences factory rooted at a given path. + */ + public static final class TestPreferencesFactory implements PreferencesFactory { + private final Preferences userPrefs; + private final Preferences systemPrefs; + + public TestPreferencesFactory(String root) { + userPrefs = new FilePreferencesImpl(root + "/user", true); + systemPrefs = new FilePreferencesImpl(root + "/system", false); + } + + public Preferences userRoot() { + return userPrefs; + } + + public Preferences systemRoot() { + return systemPrefs; + } + } + + private PreferencesFactory defaultFactory; + private File temporaryDirectory; + + @Override + public void setUp() throws Exception { + temporaryDirectory = IoUtils.createTemporaryDirectory("PreferencesTest"); + defaultFactory = Preferences.setPreferencesFactory( + new TestPreferencesFactory(temporaryDirectory.getAbsolutePath())); + } + + @Override + public void tearDown() throws Exception { + Preferences.setPreferencesFactory(defaultFactory); + } + + /** * The preferences API is designed to be hostile towards files that exist * where it wants to store its XML data. http://b/3431233 */ public void testPreferencesClobbersExistingFiles() throws Exception { - File userPrefs = new File(System.getProperty("user.home") + "/.java/.userPrefs/prefs.xml"); + final File userPrefsDir = new File(temporaryDirectory + "/user"); + final File userPrefs = new File(userPrefsDir, "prefs.xml"); + assertTrue(userPrefs.createNewFile()); FileWriter writer = new FileWriter(userPrefs); writer.write("lamb"); writer.close(); diff --git a/luni/src/test/java/libcore/java/util/zip/GZIPInputStreamTest.java b/luni/src/test/java/libcore/java/util/zip/GZIPInputStreamTest.java index a28fae5..494520a 100644 --- a/luni/src/test/java/libcore/java/util/zip/GZIPInputStreamTest.java +++ b/luni/src/test/java/libcore/java/util/zip/GZIPInputStreamTest.java @@ -18,22 +18,29 @@ package libcore.java.util.zip; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.EOFException; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; -import java.io.OutputStream; import java.util.Arrays; import java.util.Random; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import junit.framework.TestCase; +import libcore.io.IoUtils; +import libcore.io.Streams; public final class GZIPInputStreamTest extends TestCase { + + private static final byte[] HELLO_WORLD_GZIPPED = new byte[] { + 31, -117, 8, 0, 0, 0, 0, 0, 0, 0, -13, 72, -51, -55, -55, 87, 8, -49, + 47, -54, 73, 1, 0, 86, -79, 23, 74, 11, 0, 0, 0 + }; + public void testShortMessage() throws IOException { - byte[] data = new byte[] { - 31, -117, 8, 0, 0, 0, 0, 0, 0, 0, -13, 72, -51, -55, -55, 87, 8, -49, - 47, -54, 73, 1, 0, 86, -79, 23, 74, 11, 0, 0, 0 - }; - assertEquals("Hello World", new String(gunzip(data), "UTF-8")); + assertEquals("Hello World", new String(gunzip(HELLO_WORLD_GZIPPED), "UTF-8")); } public void testLongMessage() throws IOException { @@ -59,15 +66,114 @@ public final class GZIPInputStreamTest extends TestCase { in.close(); } + // https://code.google.com/p/android/issues/detail?id=63873 + public void testMultipleMembers() throws Exception { + final int length = HELLO_WORLD_GZIPPED.length; + byte[] data = new byte[length * 2]; + System.arraycopy(HELLO_WORLD_GZIPPED, 0, data, 0, length); + System.arraycopy(HELLO_WORLD_GZIPPED, 0, data, length, length); + + assertEquals("Hello WorldHello World", new String(gunzip(data), "UTF-8")); + } + + // https://code.google.com/p/android/issues/detail?id=63873 + public void testTrailingNonGzipData() throws Exception { + final int length = HELLO_WORLD_GZIPPED.length; + // 50 bytes of 0s at the end of the first message. + byte[] data = new byte[length + 50]; + System.arraycopy(HELLO_WORLD_GZIPPED, 0, data, 0, length); + assertEquals("Hello World", new String(gunzip(data), "UTF-8")); + } + + // https://code.google.com/p/android/issues/detail?id=63873 + // + // Differences from the RI: Tests show the RI ignores *some* types of partial + // data but not others and this test case fails as a result. Our implementation + // will throw if it sees the gzip magic sequence at the end of a member + // but malformed / invalid data after. + public void testTrailingHeaderAndPartialMember() throws Exception { + final int length = HELLO_WORLD_GZIPPED.length; + // Copy just the header from HELLO_WORLD_GZIPPED so that our input + // stream becomes one complete member + a header member. + byte[] data = new byte[length + 10]; + System.arraycopy(HELLO_WORLD_GZIPPED, 0, data, 0, length); + System.arraycopy(HELLO_WORLD_GZIPPED, 0, data, length, 10); + + try { + gunzip(data); + fail(); + } catch (EOFException expected) { + } + + // Copy just the header from HELLO_WORLD_GZIPPED so that our input + // stream becomes one complete member + a header member. + data = new byte[length + 18]; + System.arraycopy(HELLO_WORLD_GZIPPED, 0, data, 0, length); + System.arraycopy(HELLO_WORLD_GZIPPED, 0, data, length, 18); + + try { + gunzip(data); + fail(); + } catch (EOFException expected) { + } + } + + // https://code.google.com/p/android/issues/detail?id=66409 + public void testMultipleMembersWithCustomBufferSize() throws Exception { + final int[] memberSizes = new int[] { 1000, 2000 }; + + // We don't care what the exact contents of this file is, as long + // as the file has multiple members, and that the (compressed) size of + // the second member is larger than the size of the input buffer. + // + // There's no way to achieve this for a GZIPOutputStream so we generate + // pseudo-random sequence of bytes and assert that they don't compress + // well. + final Random r = new Random(10); + byte[] bytes = new byte[3000]; + r.nextBytes(bytes); + + File f = File.createTempFile("GZIPInputStreamTest", ".gzip"); + int offset = 0; + for (int size : memberSizes) { + GZIPOutputStream gzos = null; + try { + FileOutputStream fos = new FileOutputStream(f, true /* append */); + gzos = new GZIPOutputStream(fos, size + 1); + gzos.write(bytes, offset, size); + offset += size; + gzos.finish(); + } finally { + IoUtils.closeQuietly(gzos); + } + } + + assertTrue(f.length() > 2048); + + FileInputStream fis = new FileInputStream(f); + GZIPInputStream gzip = null; + try { + gzip = new GZIPInputStream(fis, memberSizes[0]); + byte[] unzipped = Streams.readFully(gzip); + assertTrue(Arrays.equals(bytes, unzipped)); + } finally { + IoUtils.closeQuietly(gzip); + } + } + public static byte[] gunzip(byte[] bytes) throws IOException { - InputStream in = new GZIPInputStream(new ByteArrayInputStream(bytes)); + ByteArrayInputStream bis = new ByteArrayInputStream(bytes); + InputStream in = new GZIPInputStream(bis); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int count; while ((count = in.read(buffer)) != -1) { out.write(buffer, 0, count); } + + byte[] outArray = out.toByteArray(); in.close(); - return out.toByteArray(); + + return outArray; } } diff --git a/luni/src/test/java/libcore/java/util/zip/GZIPOutputStreamTest.java b/luni/src/test/java/libcore/java/util/zip/GZIPOutputStreamTest.java index 55e45bc..3b785c9 100644 --- a/luni/src/test/java/libcore/java/util/zip/GZIPOutputStreamTest.java +++ b/luni/src/test/java/libcore/java/util/zip/GZIPOutputStreamTest.java @@ -16,17 +16,14 @@ package libcore.java.util.zip; -import java.io.ByteArrayInputStream; +import junit.framework.TestCase; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.Random; -import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; -import java.util.zip.InflaterInputStream; -import junit.framework.TestCase; public final class GZIPOutputStreamTest extends TestCase { public void testShortMessage() throws IOException { @@ -67,4 +64,15 @@ public final class GZIPOutputStreamTest extends TestCase { in.close(); } + // https://code.google.com/p/android/issues/detail?id=62589 + public void testFlushAfterFinish() throws Exception { + byte[] responseBytes = "Some data to gzip".getBytes(); + ByteArrayOutputStream output = new ByteArrayOutputStream(responseBytes.length); + GZIPOutputStream gzipOutputStream = new GZIPOutputStream(output, true); + gzipOutputStream.write(responseBytes); + gzipOutputStream.finish(); + // Calling flush() after finish() shouldn't throw. + gzipOutputStream.flush(); + gzipOutputStream.close(); + } } diff --git a/luni/src/test/java/libcore/java/util/zip/OldZipFileTest.java b/luni/src/test/java/libcore/java/util/zip/OldZipFileTest.java index 9f2864b..2104655 100644 --- a/luni/src/test/java/libcore/java/util/zip/OldZipFileTest.java +++ b/luni/src/test/java/libcore/java/util/zip/OldZipFileTest.java @@ -17,21 +17,14 @@ package libcore.java.util.zip; -import tests.support.Support_PlatformFile; -import tests.support.resource.Support_Resources; - import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; -import java.io.FilePermission; import java.io.IOException; import java.io.InputStream; -import java.io.OutputStream; -import java.security.Permission; -import java.util.Enumeration; import java.util.zip.ZipEntry; -import java.util.zip.ZipException; import java.util.zip.ZipFile; +import tests.support.resource.Support_Resources; public class OldZipFileTest extends junit.framework.TestCase { @@ -150,24 +143,15 @@ public class OldZipFileTest extends junit.framework.TestCase { @Override protected void setUp() throws IOException { // Create a local copy of the file since some tests want to alter information. - tempFileName = System.getProperty("java.io.tmpdir"); - String separator = System.getProperty("file.separator"); - if (tempFileName.charAt(tempFileName.length() - 1) == separator.charAt(0)) { - tempFileName = Support_PlatformFile.getNewPlatformFile(tempFileName, "gabba.zip"); - } else { - tempFileName = Support_PlatformFile.getNewPlatformFile( - tempFileName + separator, "gabba.zip"); - } - - File f = new File(tempFileName); - f.delete(); + File tempFile = File.createTempFile("OldZipFileTest", "zip"); + tempFileName = tempFile.getAbsolutePath(); InputStream is = Support_Resources.getStream("hyts_ZipFile.zip"); - FileOutputStream fos = new FileOutputStream(f); + FileOutputStream fos = new FileOutputStream(tempFile); byte[] rbuf = getAllBytesFromStream(is); fos.write(rbuf, 0, rbuf.length); is.close(); fos.close(); - zfile = new ZipFile(f); + zfile = new ZipFile(tempFile); } /** @@ -179,18 +163,5 @@ public class OldZipFileTest extends junit.framework.TestCase { // Note zfile is a user-defined zip file used by other tests and // should not be deleted zfile.close(); - tempFileName = System.getProperty("java.io.tmpdir"); - String separator = System.getProperty("file.separator"); - if (tempFileName.charAt(tempFileName.length() - 1) == separator - .charAt(0)) { - tempFileName = Support_PlatformFile.getNewPlatformFile( - tempFileName, "gabba.zip"); - } else { - tempFileName = Support_PlatformFile.getNewPlatformFile( - tempFileName + separator, "gabba.zip"); - } - - File f = new File(tempFileName); - f.delete(); } } diff --git a/luni/src/test/java/libcore/java/util/zip/ZipFileTest.java b/luni/src/test/java/libcore/java/util/zip/ZipFileTest.java index 60af4d0..a9ff56f 100644 --- a/luni/src/test/java/libcore/java/util/zip/ZipFileTest.java +++ b/luni/src/test/java/libcore/java/util/zip/ZipFileTest.java @@ -21,11 +21,17 @@ import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; -import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.Enumeration; +import java.util.HashSet; +import java.util.List; import java.util.Random; +import java.util.Set; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import java.util.zip.ZipException; @@ -34,6 +40,8 @@ import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import junit.framework.TestCase; +import tests.support.resource.Support_Resources; + public final class ZipFileTest extends TestCase { /** * Exercise Inflater's ability to refill the zlib's input buffer. As of this @@ -160,7 +168,7 @@ public final class ZipFileTest extends TestCase { } assertEquals(expectedLength, count); - + zip.close(); } public void testInflatingStreamsRequiringZipRefill() throws IOException { @@ -218,21 +226,23 @@ public final class ZipFileTest extends TestCase { byte[] writeBuffer = new byte[8192]; Random random = new Random(); - ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(result))); - for (int entry = 0; entry < entryCount; ++entry) { - ZipEntry ze = new ZipEntry(Integer.toHexString(entry)); - out.putNextEntry(ze); + ZipOutputStream out = createZipOutputStream(result); + try { + for (int entry = 0; entry < entryCount; ++entry) { + ZipEntry ze = new ZipEntry(Integer.toHexString(entry)); + out.putNextEntry(ze); + + for (int i = 0; i < entrySize; i += writeBuffer.length) { + random.nextBytes(writeBuffer); + int byteCount = Math.min(writeBuffer.length, entrySize - i); + out.write(writeBuffer, 0, byteCount); + } - for (int i = 0; i < entrySize; i += writeBuffer.length) { - random.nextBytes(writeBuffer); - int byteCount = Math.min(writeBuffer.length, entrySize - i); - out.write(writeBuffer, 0, byteCount); + out.closeEntry(); } - - out.closeEntry(); + } finally { + out.close(); } - - out.close(); return result; } @@ -468,4 +478,30 @@ public final class ZipFileTest extends TestCase { out.closeEntry(); out.close(); } + + /** + * RI does not allow reading of an empty zip using a {@link ZipFile}. + */ + public void testConstructorFailsWhenReadingEmptyZipArchive() throws IOException { + + File resources = Support_Resources.createTempFolder(); + File emptyZip = Support_Resources.copyFile( + resources, "java/util/zip", "EmptyArchive.zip"); + + try { + // The following should fail with an exception but if it doesn't then we need to clean + // up the resource so we need a reference to it. + ZipFile zipFile = new ZipFile(emptyZip); + + // Clean up the resource. + try { + zipFile.close(); + } catch (Exception e) { + // Ignore + } + fail(); + } catch (ZipException expected) { + // expected + } + } } diff --git a/luni/src/test/java/libcore/java/util/zip/ZipInputStreamTest.java b/luni/src/test/java/libcore/java/util/zip/ZipInputStreamTest.java index cb98322..49990a3 100644 --- a/luni/src/test/java/libcore/java/util/zip/ZipInputStreamTest.java +++ b/luni/src/test/java/libcore/java/util/zip/ZipInputStreamTest.java @@ -20,15 +20,24 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; -import java.io.OutputStream; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.Arrays; +import java.util.HashSet; +import java.util.List; import java.util.Random; +import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; + import junit.framework.TestCase; +import tests.support.resource.Support_Resources; + public final class ZipInputStreamTest extends TestCase { + public void testShortMessage() throws IOException { byte[] data = "Hello World".getBytes("UTF-8"); byte[] zipped = ZipOutputStreamTest.zip("short", data); @@ -59,4 +68,18 @@ public final class ZipInputStreamTest extends TestCase { in.close(); return out.toByteArray(); } + + /** + * Reference implementation allows reading of empty zip using a {@link ZipInputStream}. + */ + public void testReadEmpty() throws IOException { + InputStream emptyZipIn = Support_Resources.getStream("java/util/zip/EmptyArchive.zip"); + ZipInputStream in = new ZipInputStream(emptyZipIn); + try { + ZipEntry entry = in.getNextEntry(); + assertNull("An empty zip has no entries", entry); + } finally { + in.close(); + } + } } diff --git a/luni/src/test/java/libcore/java/util/zip/ZipOutputStreamTest.java b/luni/src/test/java/libcore/java/util/zip/ZipOutputStreamTest.java index e7c518f..e69f010 100644 --- a/luni/src/test/java/libcore/java/util/zip/ZipOutputStreamTest.java +++ b/luni/src/test/java/libcore/java/util/zip/ZipOutputStreamTest.java @@ -16,15 +16,16 @@ package libcore.java.util.zip; -import java.io.ByteArrayInputStream; +import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; +import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Random; import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; +import java.util.zip.ZipException; import java.util.zip.ZipOutputStream; import junit.framework.TestCase; @@ -60,4 +61,30 @@ public final class ZipOutputStreamTest extends TestCase { zippedOut.close(); return bytesOut.toByteArray(); } + + /** + * Reference implementation does NOT allow writing of an empty zip using a + * {@link ZipOutputStream}. + */ + public void testCreateEmpty() throws IOException { + File result = File.createTempFile("ZipFileTest", "zip"); + ZipOutputStream out = + new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(result))); + try { + out.close(); + fail("Close on empty stream failed to throw exception"); + } catch (ZipException e) { + // expected + } + } + + /** Regression test for null comment causing a NullPointerException during write. */ + public void testNullComment() throws IOException { + ZipOutputStream out = new ZipOutputStream(new ByteArrayOutputStream()); + out.setComment(null); + out.putNextEntry(new ZipEntry("name")); + out.write(new byte[1]); + out.closeEntry(); + out.finish(); + } } diff --git a/luni/src/test/java/libcore/javax/crypto/CipherInputStreamTest.java b/luni/src/test/java/libcore/javax/crypto/CipherInputStreamTest.java index 28d95f2..67ed36c 100644 --- a/luni/src/test/java/libcore/javax/crypto/CipherInputStreamTest.java +++ b/luni/src/test/java/libcore/javax/crypto/CipherInputStreamTest.java @@ -18,8 +18,10 @@ package libcore.javax.crypto; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; +import java.security.spec.AlgorithmParameterSpec; import java.util.Arrays; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; @@ -30,37 +32,134 @@ import junit.framework.TestCase; public final class CipherInputStreamTest extends TestCase { - private final byte[] keyBytes = { 127, -2, -95, -39, 35, 118, 121, -92 }; + private final byte[] aesKeyBytes = { + (byte) 0x50, (byte) 0x98, (byte) 0xF2, (byte) 0xC3, (byte) 0x85, (byte) 0x23, + (byte) 0xA3, (byte) 0x33, (byte) 0x50, (byte) 0x98, (byte) 0xF2, (byte) 0xC3, + (byte) 0x85, (byte) 0x23, (byte) 0xA3, (byte) 0x33, + }; + + private final byte[] aesIvBytes = { + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + }; + + private final byte[] aesCipherText = { + (byte) 0x2F, (byte) 0x2C, (byte) 0x74, (byte) 0x31, (byte) 0xFF, (byte) 0xCC, + (byte) 0x28, (byte) 0x7D, (byte) 0x59, (byte) 0xBD, (byte) 0xE5, (byte) 0x0A, + (byte) 0x30, (byte) 0x7E, (byte) 0x6A, (byte) 0x4A + }; + + private final byte[] rc4CipherText = { + (byte) 0x88, (byte) 0x01, (byte) 0xE3, (byte) 0x52, (byte) 0x7B + }; + private final String plainText = "abcde"; - private final byte[] cipherText = { 121, -124, -106, 43, -55, -67, -105, -75 }; private SecretKey key; + private SecretKey rc4Key; + private AlgorithmParameterSpec iv; @Override protected void setUp() throws Exception { - key = new SecretKeySpec(keyBytes, "DES"); + key = new SecretKeySpec(aesKeyBytes, "AES"); + rc4Key = new SecretKeySpec(aesKeyBytes, "RC4"); + iv = new IvParameterSpec(aesIvBytes); + } + + private static class MeasuringInputStream extends FilterInputStream { + private int totalRead; + + protected MeasuringInputStream(InputStream in) { + super(in); + } + + @Override + public int read() throws IOException { + int c = super.read(); + totalRead++; + return c; + } + + @Override + public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException { + int numRead = super.read(buffer, byteOffset, byteCount); + if (numRead != -1) { + totalRead += numRead; + } + return numRead; + } + + public int getTotalRead() { + return totalRead; + } + } + + public void testAvailable() throws Exception { + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + cipher.init(Cipher.DECRYPT_MODE, key, iv); + MeasuringInputStream in = new MeasuringInputStream(new ByteArrayInputStream(aesCipherText)); + InputStream cin = new CipherInputStream(in, cipher); + assertTrue(cin.read() != -1); + assertEquals(aesCipherText.length, in.getTotalRead()); + } + + public void testDecrypt_NullInput_Discarded() throws Exception { + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + cipher.init(Cipher.DECRYPT_MODE, key, iv); + InputStream in = new CipherInputStream(new ByteArrayInputStream(aesCipherText), cipher); + int discard = 3; + while (discard != 0) { + discard -= in.read(null, 0, discard); + } + byte[] bytes = readAll(in); + assertEquals(Arrays.toString(plainText.substring(3).getBytes("UTF-8")), + Arrays.toString(bytes)); } public void testEncrypt() throws Exception { - Cipher cipher = Cipher.getInstance("DES"); - cipher.init(Cipher.ENCRYPT_MODE, key); + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + cipher.init(Cipher.ENCRYPT_MODE, key, iv); InputStream in = new CipherInputStream( new ByteArrayInputStream(plainText.getBytes("UTF-8")), cipher); byte[] bytes = readAll(in); - assertEquals(Arrays.toString(cipherText), Arrays.toString(bytes)); + assertEquals(Arrays.toString(aesCipherText), Arrays.toString(bytes)); + + // Reading again shouldn't throw an exception. + assertEquals(-1, in.read()); + } + + public void testEncrypt_RC4() throws Exception { + Cipher cipher = Cipher.getInstance("RC4"); + cipher.init(Cipher.ENCRYPT_MODE, rc4Key); + InputStream in = new CipherInputStream( + new ByteArrayInputStream(plainText.getBytes("UTF-8")), cipher); + byte[] bytes = readAll(in); + assertEquals(Arrays.toString(rc4CipherText), Arrays.toString(bytes)); + + // Reading again shouldn't throw an exception. + assertEquals(-1, in.read()); } public void testDecrypt() throws Exception { - Cipher cipher = Cipher.getInstance("DES"); - cipher.init(Cipher.DECRYPT_MODE, key); - InputStream in = new CipherInputStream(new ByteArrayInputStream(cipherText), cipher); + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + cipher.init(Cipher.DECRYPT_MODE, key, iv); + InputStream in = new CipherInputStream(new ByteArrayInputStream(aesCipherText), cipher); byte[] bytes = readAll(in); - assertEquals(plainText, new String(bytes, "UTF-8")); + assertEquals(Arrays.toString(plainText.getBytes("UTF-8")), Arrays.toString(bytes)); + } + + public void testDecrypt_RC4() throws Exception { + Cipher cipher = Cipher.getInstance("RC4"); + cipher.init(Cipher.DECRYPT_MODE, rc4Key); + InputStream in = new CipherInputStream(new ByteArrayInputStream(rc4CipherText), cipher); + byte[] bytes = readAll(in); + assertEquals(Arrays.toString(plainText.getBytes("UTF-8")), Arrays.toString(bytes)); } public void testSkip() throws Exception { - Cipher cipher = Cipher.getInstance("DES"); - cipher.init(Cipher.DECRYPT_MODE, key); - InputStream in = new CipherInputStream(new ByteArrayInputStream(cipherText), cipher); - assertTrue(in.skip(5) > 0); + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + cipher.init(Cipher.DECRYPT_MODE, key, iv); + InputStream in = new CipherInputStream(new ByteArrayInputStream(aesCipherText), cipher); + assertTrue(in.skip(5) >= 0); } private byte[] readAll(InputStream in) throws IOException { @@ -75,10 +174,33 @@ public final class CipherInputStreamTest extends TestCase { public void testCipherInputStream_TruncatedInput_Failure() throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); - cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(new byte[16], "AES"), - new IvParameterSpec(new byte[16])); + cipher.init(Cipher.DECRYPT_MODE, key, iv); InputStream is = new CipherInputStream(new ByteArrayInputStream(new byte[31]), cipher); is.read(new byte[4]); is.close(); } + + public void testCipherInputStream_NullInputStream_Failure() throws Exception { + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + cipher.init(Cipher.DECRYPT_MODE, key, iv); + InputStream is = new CipherInputStream(null, cipher); + try { + is.read(); + fail("Expected NullPointerException"); + } catch (NullPointerException expected) { + } + + byte[] buffer = new byte[128]; + try { + is.read(buffer); + fail("Expected NullPointerException"); + } catch (NullPointerException expected) { + } + + try { + is.read(buffer, 0, buffer.length); + fail("Expected NullPointerException"); + } catch (NullPointerException expected) { + } + } } diff --git a/luni/src/test/java/libcore/javax/crypto/CipherTest.java b/luni/src/test/java/libcore/javax/crypto/CipherTest.java index 7922a04..c89886c 100644 --- a/luni/src/test/java/libcore/javax/crypto/CipherTest.java +++ b/luni/src/test/java/libcore/javax/crypto/CipherTest.java @@ -26,14 +26,13 @@ import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.KeyFactory; +import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.Provider; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Security; import java.security.cert.Certificate; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.RSAPrivateKeySpec; import java.security.spec.RSAPublicKeySpec; @@ -53,6 +52,7 @@ import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.ShortBufferException; +import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEParameterSpec; @@ -60,10 +60,12 @@ import javax.crypto.spec.SecretKeySpec; import junit.framework.TestCase; import libcore.java.security.StandardNames; import libcore.java.security.TestKeyStore; -import libcore.util.EmptyArray; public final class CipherTest extends TestCase { + /** GCM tag size used for tests. */ + private static final int GCM_TAG_SIZE_BITS = 96; + private static final String[] RSA_PROVIDERS = ((StandardNames.IS_RI) ? new String[] { "SunJCE" } : new String[] { "BC" , "AndroidOpenSSL" }); @@ -72,27 +74,6 @@ public final class CipherTest extends TestCase { ? new String[] { "SunJCE" } : new String[] { "BC", "AndroidOpenSSL" }); - private static final boolean IS_UNLIMITED; - static { - boolean is_unlimited; - if (StandardNames.IS_RI) { - try { - String algorithm = "PBEWITHMD5ANDTRIPLEDES"; - Cipher.getInstance(algorithm).init(getEncryptMode(algorithm), - getEncryptKey(algorithm), - getEncryptAlgorithmParameterSpec(algorithm)); - is_unlimited = true; - } catch (Exception e) { - is_unlimited = false; - System.out.println("WARNING: Some tests disabled due to lack of " - + "'Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files'"); - } - } else { - is_unlimited = true; - } - IS_UNLIMITED = is_unlimited; - } - private static boolean isSupported(String algorithm, String provider) { if (algorithm.equals("RC2")) { return false; @@ -117,12 +98,16 @@ public final class CipherTest extends TestCase { return false; } } - // stream modes CFB, CTR, CTS, OFB with PKCS5Padding don't really make sense + // stream modes CFB, CTR, CTS, OFB with PKCS5Padding or PKCS7Padding don't really make sense if (!provider.equals("AndroidOpenSSL") && (algorithm.equals("AES/CFB/PKCS5PADDING") + || algorithm.equals("AES/CFB/PKCS7PADDING") || algorithm.equals("AES/CTR/PKCS5PADDING") + || algorithm.equals("AES/CTR/PKCS7PADDING") || algorithm.equals("AES/CTS/PKCS5PADDING") - || algorithm.equals("AES/OFB/PKCS5PADDING"))) { + || algorithm.equals("AES/CTS/PKCS7PADDING") + || algorithm.equals("AES/OFB/PKCS5PADDING") + || algorithm.equals("AES/OFB/PKCS7PADDING"))) { return false; } return true; @@ -138,7 +123,7 @@ public final class CipherTest extends TestCase { return false; } // AESWRAP should be used instead, fails with BC and SunJCE otherwise. - if (algorithm.startsWith("AES")) { + if (algorithm.startsWith("AES") || algorithm.startsWith("DESEDE")) { return false; } return true; @@ -165,6 +150,12 @@ public final class CipherTest extends TestCase { if (algorithm.startsWith("AES/")) { return "AES"; } + if (algorithm.equals("GCM")) { + return "AES"; + } + if (algorithm.startsWith("DESEDE/")) { + return "DESEDE"; + } if (algorithm.equals("PBEWITHMD5AND128BITAES-CBC-OPENSSL")) { return "AES"; } @@ -240,6 +231,11 @@ public final class CipherTest extends TestCase { return algorithm.startsWith("PBE"); } + private static boolean isStreamMode(String algorithm) { + return algorithm.contains("/CTR/") || algorithm.contains("/OFB") + || algorithm.contains("/CFB"); + } + private static Map<String, Key> ENCRYPT_KEYS = new HashMap<String, Key>(); private synchronized static Key getEncryptKey(String algorithm) throws Exception { Key key = ENCRYPT_KEYS.get(algorithm); @@ -285,17 +281,24 @@ public final class CipherTest extends TestCase { static { setExpectedBlockSize("AES", 16); setExpectedBlockSize("AES/CBC/PKCS5PADDING", 16); + setExpectedBlockSize("AES/CBC/PKCS7PADDING", 16); setExpectedBlockSize("AES/CBC/NOPADDING", 16); setExpectedBlockSize("AES/CFB/PKCS5PADDING", 16); + setExpectedBlockSize("AES/CFB/PKCS7PADDING", 16); setExpectedBlockSize("AES/CFB/NOPADDING", 16); setExpectedBlockSize("AES/CTR/PKCS5PADDING", 16); + setExpectedBlockSize("AES/CTR/PKCS7PADDING", 16); setExpectedBlockSize("AES/CTR/NOPADDING", 16); setExpectedBlockSize("AES/CTS/PKCS5PADDING", 16); + setExpectedBlockSize("AES/CTS/PKCS7PADDING", 16); setExpectedBlockSize("AES/CTS/NOPADDING", 16); setExpectedBlockSize("AES/ECB/PKCS5PADDING", 16); + setExpectedBlockSize("AES/ECB/PKCS7PADDING", 16); setExpectedBlockSize("AES/ECB/NOPADDING", 16); setExpectedBlockSize("AES/OFB/PKCS5PADDING", 16); + setExpectedBlockSize("AES/OFB/PKCS7PADDING", 16); setExpectedBlockSize("AES/OFB/NOPADDING", 16); + setExpectedBlockSize("GCM", 16); setExpectedBlockSize("PBEWITHMD5AND128BITAES-CBC-OPENSSL", 16); setExpectedBlockSize("PBEWITHMD5AND192BITAES-CBC-OPENSSL", 16); setExpectedBlockSize("PBEWITHMD5AND256BITAES-CBC-OPENSSL", 16); @@ -324,6 +327,24 @@ public final class CipherTest extends TestCase { setExpectedBlockSize("PBEWITHSHA1ANDDES", 8); setExpectedBlockSize("DESEDE", 8); + setExpectedBlockSize("DESEDE/CBC/PKCS5PADDING", 8); + setExpectedBlockSize("DESEDE/CBC/PKCS7PADDING", 8); + setExpectedBlockSize("DESEDE/CBC/NOPADDING", 8); + setExpectedBlockSize("DESEDE/CFB/PKCS5PADDING", 8); + setExpectedBlockSize("DESEDE/CFB/PKCS7PADDING", 8); + setExpectedBlockSize("DESEDE/CFB/NOPADDING", 8); + setExpectedBlockSize("DESEDE/CTR/PKCS5PADDING", 8); + setExpectedBlockSize("DESEDE/CTR/PKCS7PADDING", 8); + setExpectedBlockSize("DESEDE/CTR/NOPADDING", 8); + setExpectedBlockSize("DESEDE/CTS/PKCS5PADDING", 8); + setExpectedBlockSize("DESEDE/CTS/PKCS7PADDING", 8); + setExpectedBlockSize("DESEDE/CTS/NOPADDING", 8); + setExpectedBlockSize("DESEDE/ECB/PKCS5PADDING", 8); + setExpectedBlockSize("DESEDE/ECB/PKCS7PADDING", 8); + setExpectedBlockSize("DESEDE/ECB/NOPADDING", 8); + setExpectedBlockSize("DESEDE/OFB/PKCS5PADDING", 8); + setExpectedBlockSize("DESEDE/OFB/PKCS7PADDING", 8); + setExpectedBlockSize("DESEDE/OFB/NOPADDING", 8); setExpectedBlockSize("PBEWITHSHAAND2-KEYTRIPLEDES-CBC", 8); setExpectedBlockSize("PBEWITHSHAAND3-KEYTRIPLEDES-CBC", 8); setExpectedBlockSize("PBEWITHMD5ANDTRIPLEDES", 8); @@ -423,11 +444,18 @@ public final class CipherTest extends TestCase { setExpectedOutputSize("AES", Cipher.ENCRYPT_MODE, 16); setExpectedOutputSize("AES/CBC/PKCS5PADDING", Cipher.ENCRYPT_MODE, 16); + setExpectedOutputSize("AES/CBC/PKCS7PADDING", Cipher.ENCRYPT_MODE, 16); setExpectedOutputSize("AES/CFB/PKCS5PADDING", Cipher.ENCRYPT_MODE, 16); + setExpectedOutputSize("AES/CFB/PKCS7PADDING", Cipher.ENCRYPT_MODE, 16); setExpectedOutputSize("AES/CTR/PKCS5PADDING", Cipher.ENCRYPT_MODE, 16); + setExpectedOutputSize("AES/CTR/PKCS7PADDING", Cipher.ENCRYPT_MODE, 16); setExpectedOutputSize("AES/CTS/PKCS5PADDING", Cipher.ENCRYPT_MODE, 16); + setExpectedOutputSize("AES/CTS/PKCS7PADDING", Cipher.ENCRYPT_MODE, 16); setExpectedOutputSize("AES/ECB/PKCS5PADDING", Cipher.ENCRYPT_MODE, 16); + setExpectedOutputSize("AES/ECB/PKCS7PADDING", Cipher.ENCRYPT_MODE, 16); setExpectedOutputSize("AES/OFB/PKCS5PADDING", Cipher.ENCRYPT_MODE, 16); + setExpectedOutputSize("AES/OFB/PKCS7PADDING", Cipher.ENCRYPT_MODE, 16); + setExpectedOutputSize("GCM", Cipher.ENCRYPT_MODE, GCM_TAG_SIZE_BITS / 8); setExpectedOutputSize("PBEWITHMD5AND128BITAES-CBC-OPENSSL", 16); setExpectedOutputSize("PBEWITHMD5AND192BITAES-CBC-OPENSSL", 16); setExpectedOutputSize("PBEWITHMD5AND256BITAES-CBC-OPENSSL", 16); @@ -439,17 +467,28 @@ public final class CipherTest extends TestCase { setExpectedOutputSize("PBEWITHSHAAND256BITAES-CBC-BC", 16); // AndroidOpenSSL returns zero for the non-block ciphers setExpectedOutputSize("AES/CFB/PKCS5PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0); + setExpectedOutputSize("AES/CFB/PKCS7PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0); setExpectedOutputSize("AES/CTR/PKCS5PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0); + setExpectedOutputSize("AES/CTR/PKCS7PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0); setExpectedOutputSize("AES/CTS/PKCS5PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0); + setExpectedOutputSize("AES/CTS/PKCS7PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0); setExpectedOutputSize("AES/OFB/PKCS5PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0); + setExpectedOutputSize("AES/OFB/PKCS7PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0); setExpectedOutputSize("AES", Cipher.DECRYPT_MODE, 0); setExpectedOutputSize("AES/CBC/PKCS5PADDING", Cipher.DECRYPT_MODE, 0); + setExpectedOutputSize("AES/CBC/PKCS7PADDING", Cipher.DECRYPT_MODE, 0); setExpectedOutputSize("AES/CFB/PKCS5PADDING", Cipher.DECRYPT_MODE, 0); + setExpectedOutputSize("AES/CFB/PKCS7PADDING", Cipher.DECRYPT_MODE, 0); setExpectedOutputSize("AES/CTR/PKCS5PADDING", Cipher.DECRYPT_MODE, 0); + setExpectedOutputSize("AES/CTR/PKCS7PADDING", Cipher.DECRYPT_MODE, 0); setExpectedOutputSize("AES/CTS/PKCS5PADDING", Cipher.DECRYPT_MODE, 0); + setExpectedOutputSize("AES/CTS/PKCS7PADDING", Cipher.DECRYPT_MODE, 0); setExpectedOutputSize("AES/ECB/PKCS5PADDING", Cipher.DECRYPT_MODE, 0); + setExpectedOutputSize("AES/ECB/PKCS7PADDING", Cipher.DECRYPT_MODE, 0); setExpectedOutputSize("AES/OFB/PKCS5PADDING", Cipher.DECRYPT_MODE, 0); + setExpectedOutputSize("AES/OFB/PKCS7PADDING", Cipher.DECRYPT_MODE, 0); + setExpectedOutputSize("GCM", Cipher.DECRYPT_MODE, 0); setExpectedOutputSize("PBEWITHMD5AND128BITAES-CBC-OPENSSL", Cipher.DECRYPT_MODE, 0); setExpectedOutputSize("PBEWITHMD5AND192BITAES-CBC-OPENSSL", Cipher.DECRYPT_MODE, 0); setExpectedOutputSize("PBEWITHMD5AND256BITAES-CBC-OPENSSL", Cipher.DECRYPT_MODE, 0); @@ -461,7 +500,13 @@ public final class CipherTest extends TestCase { setExpectedOutputSize("PBEWITHSHAAND256BITAES-CBC-BC", Cipher.DECRYPT_MODE, 0); // AndroidOpenSSL returns the block size for the block ciphers setExpectedOutputSize("AES/CBC/PKCS5PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 16); + setExpectedOutputSize("AES/CBC/PKCS7PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 16); setExpectedOutputSize("AES/ECB/PKCS5PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 16); + setExpectedOutputSize("AES/ECB/PKCS7PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 16); + setExpectedOutputSize("DESEDE/CBC/PKCS5PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 8); + setExpectedOutputSize("DESEDE/CBC/PKCS7PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 8); + setExpectedOutputSize("DESEDE/ECB/PKCS5PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 8); + setExpectedOutputSize("DESEDE/ECB/PKCS7PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 8); if (StandardNames.IS_RI) { setExpectedOutputSize("AESWRAP", Cipher.WRAP_MODE, 8); @@ -486,13 +531,44 @@ public final class CipherTest extends TestCase { setExpectedOutputSize("PBEWITHMD5ANDDES", Cipher.DECRYPT_MODE, 0); setExpectedOutputSize("PBEWITHSHA1ANDDES", Cipher.DECRYPT_MODE, 0); + setExpectedOutputSize("DESEDE/CBC/NOPADDING", 0); + setExpectedOutputSize("DESEDE/CFB/NOPADDING", 0); + setExpectedOutputSize("DESEDE/CTR/NOPADDING", 0); + setExpectedOutputSize("DESEDE/CTS/NOPADDING", 0); + setExpectedOutputSize("DESEDE/ECB/NOPADDING", 0); + setExpectedOutputSize("DESEDE/OFB/NOPADDING", 0); + setExpectedOutputSize("DESEDE", Cipher.ENCRYPT_MODE, 8); + setExpectedOutputSize("DESEDE/CBC/PKCS5PADDING", Cipher.ENCRYPT_MODE, 8); + setExpectedOutputSize("DESEDE/CBC/PKCS7PADDING", Cipher.ENCRYPT_MODE, 8); + setExpectedOutputSize("DESEDE/CFB/PKCS5PADDING", Cipher.ENCRYPT_MODE, 8); + setExpectedOutputSize("DESEDE/CFB/PKCS7PADDING", Cipher.ENCRYPT_MODE, 8); + setExpectedOutputSize("DESEDE/CTR/PKCS5PADDING", Cipher.ENCRYPT_MODE, 8); + setExpectedOutputSize("DESEDE/CTR/PKCS7PADDING", Cipher.ENCRYPT_MODE, 8); + setExpectedOutputSize("DESEDE/CTS/PKCS5PADDING", Cipher.ENCRYPT_MODE, 8); + setExpectedOutputSize("DESEDE/CTS/PKCS7PADDING", Cipher.ENCRYPT_MODE, 8); + setExpectedOutputSize("DESEDE/ECB/PKCS5PADDING", Cipher.ENCRYPT_MODE, 8); + setExpectedOutputSize("DESEDE/ECB/PKCS7PADDING", Cipher.ENCRYPT_MODE, 8); + setExpectedOutputSize("DESEDE/OFB/PKCS5PADDING", Cipher.ENCRYPT_MODE, 8); + setExpectedOutputSize("DESEDE/OFB/PKCS7PADDING", Cipher.ENCRYPT_MODE, 8); setExpectedOutputSize("PBEWITHSHAAND2-KEYTRIPLEDES-CBC", Cipher.ENCRYPT_MODE, 8); setExpectedOutputSize("PBEWITHSHAAND3-KEYTRIPLEDES-CBC", Cipher.ENCRYPT_MODE, 8); setExpectedOutputSize("PBEWITHMD5ANDTRIPLEDES", Cipher.ENCRYPT_MODE, 8); setExpectedOutputSize("PBEWITHSHA1ANDDESEDE", Cipher.ENCRYPT_MODE, 8); setExpectedOutputSize("DESEDE", Cipher.DECRYPT_MODE, 0); + setExpectedOutputSize("DESEDE/CBC/PKCS5PADDING", Cipher.DECRYPT_MODE, 0); + setExpectedOutputSize("DESEDE/CBC/PKCS7PADDING", Cipher.DECRYPT_MODE, 0); + setExpectedOutputSize("DESEDE/CFB/PKCS5PADDING", Cipher.DECRYPT_MODE, 0); + setExpectedOutputSize("DESEDE/CFB/PKCS7PADDING", Cipher.DECRYPT_MODE, 0); + setExpectedOutputSize("DESEDE/CTR/PKCS5PADDING", Cipher.DECRYPT_MODE, 0); + setExpectedOutputSize("DESEDE/CTR/PKCS7PADDING", Cipher.DECRYPT_MODE, 0); + setExpectedOutputSize("DESEDE/CTS/PKCS5PADDING", Cipher.DECRYPT_MODE, 0); + setExpectedOutputSize("DESEDE/CTS/PKCS7PADDING", Cipher.DECRYPT_MODE, 0); + setExpectedOutputSize("DESEDE/ECB/PKCS5PADDING", Cipher.DECRYPT_MODE, 0); + setExpectedOutputSize("DESEDE/ECB/PKCS7PADDING", Cipher.DECRYPT_MODE, 0); + setExpectedOutputSize("DESEDE/OFB/PKCS5PADDING", Cipher.DECRYPT_MODE, 0); + setExpectedOutputSize("DESEDE/OFB/PKCS7PADDING", Cipher.DECRYPT_MODE, 0); setExpectedOutputSize("PBEWITHSHAAND2-KEYTRIPLEDES-CBC", Cipher.DECRYPT_MODE, 0); setExpectedOutputSize("PBEWITHSHAAND3-KEYTRIPLEDES-CBC", Cipher.DECRYPT_MODE, 0); setExpectedOutputSize("PBEWITHMD5ANDTRIPLEDES", Cipher.DECRYPT_MODE, 0); @@ -542,6 +618,8 @@ public final class CipherTest extends TestCase { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + private static byte[] EIGHT_BYTE_BLOCK_PLAIN_TEXT = new byte[] { 0x0a, 0x0b, 0x0c, 0x00, + 0x00, 0x00, 0x00, 0x00 }; private static byte[] PKCS1_BLOCK_TYPE_00_PADDED_PLAIN_TEXT = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -638,6 +716,11 @@ public final class CipherTest extends TestCase { || algorithm.equals("AES/ECB/NOPADDING")) { return SIXTEEN_BYTE_BLOCK_PLAIN_TEXT; } + if (algorithm.equals("DESEDE") + || algorithm.equals("DESEDE/CBC/NOPADDING") + || algorithm.equals("DESEDE/ECB/NOPADDING")) { + return EIGHT_BYTE_BLOCK_PLAIN_TEXT; + } return ORIGINAL_PLAIN_TEXT; } @@ -649,6 +732,11 @@ public final class CipherTest extends TestCase { || algorithm.equals("AES/ECB/NOPADDING")) { return SIXTEEN_BYTE_BLOCK_PLAIN_TEXT; } + if (algorithm.equals("DESEDE") + || algorithm.equals("DESEDE/CBC/NOPADDING") + || algorithm.equals("DESEDE/ECB/NOPADDING")) { + return EIGHT_BYTE_BLOCK_PLAIN_TEXT; + } // BC strips the leading 0 for us even when NoPadding is specified if (!provider.equals("BC") && algorithm.equals("RSA/ECB/NOPADDING")) { return PKCS1_BLOCK_TYPE_00_PADDED_PLAIN_TEXT; @@ -662,8 +750,14 @@ public final class CipherTest extends TestCase { new SecureRandom().nextBytes(salt); return new PBEParameterSpec(salt, 1024); } + if (algorithm.equals("GCM")) { + final byte[] iv = new byte[8]; + new SecureRandom().nextBytes(iv); + return new GCMParameterSpec(GCM_TAG_SIZE_BITS, iv); + } if (algorithm.equals("AES/CBC/NOPADDING") || algorithm.equals("AES/CBC/PKCS5PADDING") + || algorithm.equals("AES/CBC/PKCS7PADDING") || algorithm.equals("AES/CFB/NOPADDING") || algorithm.equals("AES/CTR/NOPADDING") || algorithm.equals("AES/CTS/NOPADDING") @@ -672,6 +766,17 @@ public final class CipherTest extends TestCase { new SecureRandom().nextBytes(iv); return new IvParameterSpec(iv); } + if (algorithm.equals("DESEDE/CBC/NOPADDING") + || algorithm.equals("DESEDE/CBC/PKCS5PADDING") + || algorithm.equals("DESEDE/CBC/PKCS7PADDING") + || algorithm.equals("DESEDE/CFB/NOPADDING") + || algorithm.equals("DESEDE/CTR/NOPADDING") + || algorithm.equals("DESEDE/CTS/NOPADDING") + || algorithm.equals("DESEDE/OFB/NOPADDING")) { + final byte[] iv = new byte[8]; + new SecureRandom().nextBytes(iv); + return new IvParameterSpec(iv); + } return null; } @@ -686,11 +791,193 @@ public final class CipherTest extends TestCase { } byte[] iv = encryptCipher.getIV(); if (iv != null) { + if ("GCM".equals(algorithm)) { + return new GCMParameterSpec(GCM_TAG_SIZE_BITS, iv); + } return new IvParameterSpec(iv); } return null; } + /* + * This must be below everything else to make sure the other static blocks + * have run first. + */ + private static final boolean IS_UNLIMITED; + static { + boolean is_unlimited; + if (StandardNames.IS_RI) { + try { + String algorithm = "PBEWITHMD5ANDTRIPLEDES"; + Cipher.getInstance(algorithm).init(getEncryptMode(algorithm), + getEncryptKey(algorithm), + getEncryptAlgorithmParameterSpec(algorithm)); + is_unlimited = true; + } catch (Exception e) { + is_unlimited = false; + System.out.println("WARNING: Some tests disabled due to lack of " + + "'Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files'"); + } + } else { + is_unlimited = true; + } + IS_UNLIMITED = is_unlimited; + } + + private static abstract class MockProvider extends Provider { + public MockProvider(String name) { + super(name, 1.0, "Mock provider used for testing"); + setup(); + } + + public abstract void setup(); + } + + public void testCipher_getInstance_SuppliedProviderNotRegistered_Success() throws Exception { + Provider mockProvider = new MockProvider("MockProvider") { + public void setup() { + put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName()); + } + }; + + { + Cipher c = Cipher.getInstance("FOO", mockProvider); + c.init(Cipher.ENCRYPT_MODE, new MockKey()); + assertEquals(mockProvider, c.getProvider()); + } + } + + public void testCipher_getInstance_SuppliedProviderNotRegistered_MultipartTransform_Success() + throws Exception { + Provider mockProvider = new MockProvider("MockProvider") { + public void setup() { + put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName()); + } + }; + + { + Cipher c = Cipher.getInstance("FOO/FOO/FOO", mockProvider); + c.init(Cipher.ENCRYPT_MODE, new MockKey()); + assertEquals(mockProvider, c.getProvider()); + } + } + + public void testCipher_getInstance_OnlyUsesSpecifiedProvider_SameNameAndClass_Success() + throws Exception { + Provider mockProvider = new MockProvider("MockProvider") { + public void setup() { + put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName()); + } + }; + + Security.addProvider(mockProvider); + try { + { + Provider mockProvider2 = new MockProvider("MockProvider") { + public void setup() { + put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName()); + } + }; + Cipher c = Cipher.getInstance("FOO", mockProvider2); + assertEquals(mockProvider2, c.getProvider()); + } + } finally { + Security.removeProvider(mockProvider.getName()); + } + } + + public void testCipher_getInstance_DelayedInitialization_KeyType() throws Exception { + Provider mockProviderSpecific = new MockProvider("MockProviderSpecific") { + public void setup() { + put("Cipher.FOO", MockCipherSpi.SpecificKeyTypes.class.getName()); + put("Cipher.FOO SupportedKeyClasses", MockKey.class.getName()); + } + }; + Provider mockProviderSpecific2 = new MockProvider("MockProviderSpecific2") { + public void setup() { + put("Cipher.FOO", MockCipherSpi.SpecificKeyTypes2.class.getName()); + put("Cipher.FOO SupportedKeyClasses", MockKey2.class.getName()); + } + }; + Provider mockProviderAll = new MockProvider("MockProviderAll") { + public void setup() { + put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName()); + } + }; + + Security.addProvider(mockProviderSpecific); + Security.addProvider(mockProviderSpecific2); + Security.addProvider(mockProviderAll); + + try { + { + System.out.println(Arrays.deepToString(Security.getProviders("Cipher.FOO"))); + Cipher c = Cipher.getInstance("FOO"); + c.init(Cipher.ENCRYPT_MODE, new MockKey()); + assertEquals(mockProviderSpecific, c.getProvider()); + + try { + c.init(Cipher.ENCRYPT_MODE, new MockKey2()); + assertEquals(mockProviderSpecific2, c.getProvider()); + if (StandardNames.IS_RI) { + fail("RI was broken before; fix tests now that it works!"); + } + } catch (InvalidKeyException e) { + if (!StandardNames.IS_RI) { + fail("Non-RI should select the right provider"); + } + } + } + + { + Cipher c = Cipher.getInstance("FOO"); + c.init(Cipher.ENCRYPT_MODE, new Key() { + @Override + public String getAlgorithm() { + throw new UnsupportedOperationException("not implemented"); + } + + @Override + public String getFormat() { + throw new UnsupportedOperationException("not implemented"); + } + + @Override + public byte[] getEncoded() { + throw new UnsupportedOperationException("not implemented"); + } + }); + assertEquals(mockProviderAll, c.getProvider()); + } + + { + Cipher c = Cipher.getInstance("FOO"); + assertEquals(mockProviderSpecific, c.getProvider()); + } + } finally { + Security.removeProvider(mockProviderSpecific.getName()); + Security.removeProvider(mockProviderSpecific2.getName()); + Security.removeProvider(mockProviderAll.getName()); + } + } + + public void testCipher_getInstance_WrongType_Failure() throws Exception { + Provider mockProviderInvalid = new MockProvider("MockProviderInvalid") { + public void setup() { + put("Cipher.FOO", Object.class.getName()); + } + }; + + Security.addProvider(mockProviderInvalid); + try { + Cipher.getInstance("FOO"); + fail("Should not find any matching providers"); + } catch (NoSuchAlgorithmException expected) { + } finally { + Security.removeProvider(mockProviderInvalid.getName()); + } + } + public void test_getInstance() throws Exception { final ByteArrayOutputStream errBuffer = new ByteArrayOutputStream(); PrintStream out = new PrintStream(errBuffer); @@ -723,7 +1010,9 @@ public final class CipherTest extends TestCase { if (!seenBaseCipherNames.contains(baseCipherName)) { seenCiphersWithModeAndPadding.add(baseCipherName); } - continue; + if (!"AndroidOpenSSL".equals(provider.getName())) { + continue; + } } try { @@ -832,11 +1121,18 @@ public final class CipherTest extends TestCase { } } + test_Cipher_init_NullParameters(c, encryptMode, encryptKey); + c.init(encryptMode, encryptKey, encryptSpec); assertEquals(cipherID + " getBlockSize() encryptMode", getExpectedBlockSize(algorithm, encryptMode, providerName), c.getBlockSize()); assertEquals(cipherID + " getOutputSize(0) encryptMode", getExpectedOutputSize(algorithm, encryptMode, providerName), c.getOutputSize(0)); + if ((algorithm.endsWith("/PKCS5PADDING") || algorithm.endsWith("/PKCS7PADDING")) + && isStreamMode(algorithm)) { + assertEquals(getExpectedOutputSize(algorithm, encryptMode, providerName), + c.doFinal(new byte[1]).length); + } final AlgorithmParameterSpec decryptSpec = getDecryptAlgorithmParameterSpec(encryptSpec, c); int decryptMode = getDecryptMode(algorithm); @@ -856,6 +1152,11 @@ public final class CipherTest extends TestCase { assertEquals(cipherID + " getIV()", Arrays.toString(((IvParameterSpec) decryptSpec).getIV()), Arrays.toString(c.getIV())); + } else if (decryptSpec instanceof GCMParameterSpec) { + assertNotNull(c.getIV()); + assertEquals(cipherID + " getIV()", + Arrays.toString(((GCMParameterSpec) decryptSpec).getIV()), + Arrays.toString(c.getIV())); } else { try { assertNull(cipherID + " getIV()", c.getIV()); @@ -885,7 +1186,9 @@ public final class CipherTest extends TestCase { assertNull(cipherID, c.getExemptionMechanism()); // Test wrapping a key. Every cipher should be able to wrap. Except those that can't. - if (isSupportedForWrapping(algorithm)) { + /* Bouncycastle is broken for wrapping because getIV() fails. */ + if (isSupportedForWrapping(algorithm) + && !algorithm.equals("GCM") && !providerName.equals("BC")) { // Generate a small SecretKey for AES. KeyGenerator kg = KeyGenerator.getInstance("AES"); kg.init(128); @@ -910,11 +1213,58 @@ public final class CipherTest extends TestCase { if (!isOnlyWrappingAlgorithm(algorithm)) { c.init(Cipher.ENCRYPT_MODE, encryptKey, encryptSpec); byte[] cipherText = c.doFinal(getActualPlainText(algorithm)); + byte[] cipherText2 = c.doFinal(getActualPlainText(algorithm)); + assertEquals(cipherID, + Arrays.toString(cipherText), + Arrays.toString(cipherText2)); c.init(Cipher.DECRYPT_MODE, getDecryptKey(algorithm), decryptSpec); byte[] decryptedPlainText = c.doFinal(cipherText); assertEquals(cipherID, Arrays.toString(getExpectedPlainText(algorithm, providerName)), Arrays.toString(decryptedPlainText)); + byte[] decryptedPlainText2 = c.doFinal(cipherText); + assertEquals(cipherID, + Arrays.toString(decryptedPlainText), + Arrays.toString(decryptedPlainText2)); + } + } + + /** + * Try various .init(...) calls with null parameters to make sure it is + * handled. + */ + private void test_Cipher_init_NullParameters(Cipher c, int encryptMode, Key encryptKey) + throws Exception { + try { + c.init(encryptMode, encryptKey, (AlgorithmParameterSpec) null); + } catch (InvalidAlgorithmParameterException e) { + if (!isPBE(c.getAlgorithm())) { + throw e; + } + } + + try { + c.init(encryptMode, encryptKey, (AlgorithmParameterSpec) null, (SecureRandom) null); + } catch (InvalidAlgorithmParameterException e) { + if (!isPBE(c.getAlgorithm())) { + throw e; + } + } + + try { + c.init(encryptMode, encryptKey, (AlgorithmParameters) null); + } catch (InvalidAlgorithmParameterException e) { + if (!isPBE(c.getAlgorithm())) { + throw e; + } + } + + try { + c.init(encryptMode, encryptKey, (AlgorithmParameters) null, (SecureRandom) null); + } catch (InvalidAlgorithmParameterException e) { + if (!isPBE(c.getAlgorithm())) { + throw e; + } } } @@ -2135,7 +2485,7 @@ public final class CipherTest extends TestCase { }; private static class CipherTestParam { - public final String mode; + public final String transformation; public final byte[] key; @@ -2147,9 +2497,9 @@ public final class CipherTest extends TestCase { public final byte[] plaintextPadded; - public CipherTestParam(String mode, byte[] key, byte[] iv, byte[] plaintext, + public CipherTestParam(String transformation, byte[] key, byte[] iv, byte[] plaintext, byte[] plaintextPadded, byte[] ciphertext) { - this.mode = mode; + this.transformation = transformation; this.key = key; this.iv = iv; this.plaintext = plaintext; @@ -2160,13 +2510,24 @@ public final class CipherTest extends TestCase { private static List<CipherTestParam> CIPHER_TEST_PARAMS = new ArrayList<CipherTestParam>(); static { - CIPHER_TEST_PARAMS.add(new CipherTestParam("AES/ECB", AES_128_KEY, + CIPHER_TEST_PARAMS.add(new CipherTestParam("AES/ECB/PKCS5Padding", AES_128_KEY, + null, + AES_128_ECB_PKCS5Padding_TestVector_1_Plaintext, + AES_128_ECB_PKCS5Padding_TestVector_1_Plaintext_Padded, + AES_128_ECB_PKCS5Padding_TestVector_1_Encrypted)); + // PKCS#5 is assumed to be equivalent to PKCS#7 -- same test vectors are thus used for both. + CIPHER_TEST_PARAMS.add(new CipherTestParam("AES/ECB/PKCS7Padding", AES_128_KEY, null, AES_128_ECB_PKCS5Padding_TestVector_1_Plaintext, AES_128_ECB_PKCS5Padding_TestVector_1_Plaintext_Padded, AES_128_ECB_PKCS5Padding_TestVector_1_Encrypted)); if (IS_UNLIMITED) { - CIPHER_TEST_PARAMS.add(new CipherTestParam("AES/CBC", AES_256_KEY, + CIPHER_TEST_PARAMS.add(new CipherTestParam("AES/CBC/PKCS5Padding", AES_256_KEY, + AES_256_CBC_PKCS5Padding_TestVector_1_IV, + AES_256_CBC_PKCS5Padding_TestVector_1_Plaintext, + AES_256_CBC_PKCS5Padding_TestVector_1_Plaintext_Padded, + AES_256_CBC_PKCS5Padding_TestVector_1_Ciphertext)); + CIPHER_TEST_PARAMS.add(new CipherTestParam("AES/CBC/PKCS7Padding", AES_256_KEY, AES_256_CBC_PKCS5Padding_TestVector_1_IV, AES_256_CBC_PKCS5Padding_TestVector_1_Plaintext, AES_256_CBC_PKCS5Padding_TestVector_1_Plaintext_Padded, @@ -2187,7 +2548,7 @@ public final class CipherTest extends TestCase { try { checkCipher(p, provider); } catch (Exception e) { - out.append("Error encountered checking " + p.mode + ", keySize=" + out.append("Error encountered checking " + p.transformation + ", keySize=" + (p.key.length * 8) + " with provider " + provider + "\n"); @@ -2202,7 +2563,7 @@ public final class CipherTest extends TestCase { private void checkCipher(CipherTestParam p, String provider) throws Exception { SecretKey key = new SecretKeySpec(p.key, "AES"); - Cipher c = Cipher.getInstance(p.mode + "/PKCS5Padding", provider); + Cipher c = Cipher.getInstance(p.transformation, provider); AlgorithmParameterSpec spec = null; if (p.iv != null) { spec = new IvParameterSpec(p.iv); @@ -2224,16 +2585,16 @@ public final class CipherTest extends TestCase { } byte[] emptyPlainText = c.doFinal(emptyCipherText); - assertEquals(Arrays.toString(EmptyArray.BYTE), Arrays.toString(emptyPlainText)); + assertEquals(Arrays.toString(new byte[0]), Arrays.toString(emptyPlainText)); // empty decrypt { if (StandardNames.IS_RI) { - assertEquals(Arrays.toString(EmptyArray.BYTE), + assertEquals(Arrays.toString(new byte[0]), Arrays.toString(c.doFinal())); - c.update(EmptyArray.BYTE); - assertEquals(Arrays.toString(EmptyArray.BYTE), + c.update(new byte[0]); + assertEquals(Arrays.toString(new byte[0]), Arrays.toString(c.doFinal())); } else if (provider.equals("BC")) { try { @@ -2242,7 +2603,7 @@ public final class CipherTest extends TestCase { } catch (IllegalBlockSizeException expected) { } try { - c.update(EmptyArray.BYTE); + c.update(new byte[0]); c.doFinal(); fail(); } catch (IllegalBlockSizeException expected) { @@ -2250,7 +2611,7 @@ public final class CipherTest extends TestCase { } else if (provider.equals("AndroidOpenSSL")) { assertNull(c.doFinal()); - c.update(EmptyArray.BYTE); + c.update(new byte[0]); assertNull(c.doFinal()); } else { throw new AssertionError("Define your behavior here for " + provider); @@ -2287,11 +2648,13 @@ public final class CipherTest extends TestCase { Arrays.toString(Arrays.copyOfRange(actualPlaintext, 1, p.plaintext.length + 1))); } - Cipher cNoPad = Cipher.getInstance(p.mode + "/NoPadding", provider); + Cipher cNoPad = Cipher.getInstance( + getCipherTransformationWithNoPadding(p.transformation), provider); cNoPad.init(Cipher.DECRYPT_MODE, key, spec); final byte[] actualPlaintextPadded = cNoPad.doFinal(p.ciphertext); - assertEquals(Arrays.toString(p.plaintextPadded), Arrays.toString(actualPlaintextPadded)); + assertEquals(provider + ":" + cNoPad.getAlgorithm(), Arrays.toString(p.plaintextPadded), + Arrays.toString(actualPlaintextPadded)); // Test wrapping a key. Every cipher should be able to wrap. { @@ -2316,6 +2679,23 @@ public final class CipherTest extends TestCase { } } + /** + * Gets the Cipher transformation with the same algorithm and mode as the provided one but + * which uses no padding. + */ + private static String getCipherTransformationWithNoPadding(String transformation) { + // The transformation is assumed to be in the Algorithm/Mode/Padding format. + int paddingModeDelimiterIndex = transformation.lastIndexOf('/'); + if (paddingModeDelimiterIndex == -1) { + fail("No padding mode delimiter: " + transformation); + } + String paddingMode = transformation.substring(paddingModeDelimiterIndex + 1); + if (!paddingMode.toLowerCase().endsWith("padding")) { + fail("No padding mode specified:" + transformation); + } + return transformation.substring(0, paddingModeDelimiterIndex) + "/NoPadding"; + } + public void testCipher_updateAAD_BeforeInit_Failure() throws Exception { Cipher c = Cipher.getInstance("AES/ECB/NoPadding"); @@ -2405,7 +2785,7 @@ public final class CipherTest extends TestCase { try { checkCipher_ShortBlock_Failure(p, provider); } catch (Exception e) { - out.append("Error encountered checking " + p.mode + ", keySize=" + out.append("Error encountered checking " + p.transformation + ", keySize=" + (p.key.length * 8) + " with provider " + provider + "\n"); e.printStackTrace(out); @@ -2419,7 +2799,8 @@ public final class CipherTest extends TestCase { private void checkCipher_ShortBlock_Failure(CipherTestParam p, String provider) throws Exception { SecretKey key = new SecretKeySpec(p.key, "AES"); - Cipher c = Cipher.getInstance(p.mode + "/NoPadding", provider); + Cipher c = Cipher.getInstance( + getCipherTransformationWithNoPadding(p.transformation), provider); if (c.getBlockSize() == 0) { return; } @@ -2427,7 +2808,8 @@ public final class CipherTest extends TestCase { c.init(Cipher.ENCRYPT_MODE, key); try { c.doFinal(new byte[] { 0x01, 0x02, 0x03 }); - fail("Should throw IllegalBlockSizeException on wrong-sized block"); + fail("Should throw IllegalBlockSizeException on wrong-sized block; provider=" + + provider); } catch (IllegalBlockSizeException expected) { } } @@ -2495,6 +2877,7 @@ public final class CipherTest extends TestCase { private void testAES_ECB_NoPadding_IncrementalUpdate_Success(String provider) throws Exception { SecretKey key = new SecretKeySpec(AES_128_KEY, "AES"); Cipher c = Cipher.getInstance("AES/ECB/NoPadding", provider); + assertEquals(provider, c.getProvider().getName()); c.init(Cipher.ENCRYPT_MODE, key); for (int i = 0; i < AES_128_ECB_PKCS5Padding_TestVector_1_Plaintext_Padded.length - 1; i++) { @@ -2506,10 +2889,11 @@ public final class CipherTest extends TestCase { final byte[] output = c.doFinal(AES_128_ECB_PKCS5Padding_TestVector_1_Plaintext_Padded, AES_128_ECB_PKCS5Padding_TestVector_1_Plaintext_Padded.length - 1, 1); - assertNotNull(output); - assertEquals(AES_128_ECB_PKCS5Padding_TestVector_1_Plaintext_Padded.length, output.length); + assertNotNull(provider, output); + assertEquals(provider, AES_128_ECB_PKCS5Padding_TestVector_1_Plaintext_Padded.length, + output.length); - assertTrue(Arrays.equals(AES_128_ECB_PKCS5Padding_TestVector_1_Encrypted, output)); + assertTrue(provider, Arrays.equals(AES_128_ECB_PKCS5Padding_TestVector_1_Encrypted, output)); } private static final byte[] AES_IV_ZEROES = new byte[] { @@ -2531,7 +2915,7 @@ public final class CipherTest extends TestCase { AlgorithmParameterSpec spec = new IvParameterSpec(AES_IV_ZEROES); try { c.init(Cipher.ENCRYPT_MODE, key, spec); - fail("Should not accept an IV in ECB mode"); + fail("Should not accept an IV in ECB mode; provider=" + provider); } catch (InvalidAlgorithmParameterException expected) { } } diff --git a/luni/src/test/java/libcore/javax/crypto/KeyGeneratorTest.java b/luni/src/test/java/libcore/javax/crypto/KeyGeneratorTest.java index 29efd3a..8bbd548 100644 --- a/luni/src/test/java/libcore/javax/crypto/KeyGeneratorTest.java +++ b/luni/src/test/java/libcore/javax/crypto/KeyGeneratorTest.java @@ -114,6 +114,8 @@ public class KeyGeneratorTest extends TestCase { putKeySize("HmacMD5", 1025); putKeySize("HmacSHA1", 1); putKeySize("HmacSHA1", 1025); + putKeySize("HmacSHA224", 40); + putKeySize("HmacSHA224", 1025); putKeySize("HmacSHA256", 40); putKeySize("HmacSHA256", 1025); putKeySize("HmacSHA384", 40); diff --git a/luni/src/test/java/libcore/javax/crypto/MockCipherSpi.java b/luni/src/test/java/libcore/javax/crypto/MockCipherSpi.java new file mode 100644 index 0000000..6742cf3 --- /dev/null +++ b/luni/src/test/java/libcore/javax/crypto/MockCipherSpi.java @@ -0,0 +1,136 @@ +/* + * Copyright 2013 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.javax.crypto; + +import java.security.AlgorithmParameters; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.spec.AlgorithmParameterSpec; + +import javax.crypto.BadPaddingException; +import javax.crypto.CipherSpi; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.ShortBufferException; + +/** + * Mock CipherSpi used by {@link CipherTest}. + */ +public class MockCipherSpi extends CipherSpi { + public static class SpecificKeyTypes extends MockCipherSpi { + @Override + public void checkKeyType(Key key) throws InvalidKeyException { + if (!(key instanceof MockKey)) { + throw new InvalidKeyException("Must be MockKey!"); + } + } + } + + public static class SpecificKeyTypes2 extends MockCipherSpi { + @Override + public void checkKeyType(Key key) throws InvalidKeyException { + System.err.println("Checking key of type " + key.getClass().getName()); + if (!(key instanceof MockKey2)) { + throw new InvalidKeyException("Must be MockKey2!"); + } + } + } + + public static class AllKeyTypes extends MockCipherSpi { + } + + public void checkKeyType(Key key) throws InvalidKeyException { + } + + @Override + protected void engineSetMode(String mode) throws NoSuchAlgorithmException { + if (!"FOO".equals(mode)) { + throw new UnsupportedOperationException("not implemented"); + } + } + + @Override + protected void engineSetPadding(String padding) throws NoSuchPaddingException { + if (!"FOO".equals(padding)) { + throw new UnsupportedOperationException("not implemented"); + } + } + + @Override + protected int engineGetBlockSize() { + throw new UnsupportedOperationException("not implemented"); + } + + @Override + protected int engineGetOutputSize(int inputLen) { + throw new UnsupportedOperationException("not implemented"); + } + + @Override + protected byte[] engineGetIV() { + throw new UnsupportedOperationException("not implemented"); + } + + @Override + protected AlgorithmParameters engineGetParameters() { + throw new UnsupportedOperationException("not implemented"); + } + + @Override + protected void engineInit(int opmode, Key key, SecureRandom random) throws InvalidKeyException { + checkKeyType(key); + } + + @Override + protected void engineInit(int opmode, Key key, AlgorithmParameterSpec params, + SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { + checkKeyType(key); + } + + @Override + protected void engineInit(int opmode, Key key, AlgorithmParameters params, SecureRandom random) + throws InvalidKeyException, InvalidAlgorithmParameterException { + checkKeyType(key); + } + + @Override + protected byte[] engineUpdate(byte[] input, int inputOffset, int inputLen) { + throw new UnsupportedOperationException("not implemented"); + } + + @Override + protected int engineUpdate(byte[] input, int inputOffset, int inputLen, byte[] output, + int outputOffset) throws ShortBufferException { + throw new UnsupportedOperationException("not implemented"); + } + + @Override + protected byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen) + throws IllegalBlockSizeException, BadPaddingException { + throw new UnsupportedOperationException("not implemented"); + } + + @Override + protected int engineDoFinal(byte[] input, int inputOffset, int inputLen, byte[] output, + int outputOffset) throws ShortBufferException, IllegalBlockSizeException, + BadPaddingException { + throw new UnsupportedOperationException("not implemented"); + } +} diff --git a/luni/src/test/java/libcore/sqlite/OldExceptionTest.java b/luni/src/test/java/libcore/javax/crypto/MockKey.java index dddfd6b..248e2de 100644 --- a/luni/src/test/java/libcore/sqlite/OldExceptionTest.java +++ b/luni/src/test/java/libcore/javax/crypto/MockKey.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2008 The Android Open Source Project + * Copyright 2013 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. @@ -14,26 +14,27 @@ * limitations under the License. */ -package libcore.sqlite; +package libcore.javax.crypto; -import SQLite.Database; -import SQLite.Exception; +import java.security.Key; -public final class OldExceptionTest extends OldSQLiteTest { - - private Database db = null; +/** + * A mock Key class used for testing. + */ +@SuppressWarnings("serial") +public class MockKey implements Key { + @Override + public String getAlgorithm() { + throw new UnsupportedOperationException("not implemented"); + } - @Override public void setUp() throws java.lang.Exception { - super.setUp(); - db = new Database(); + @Override + public String getFormat() { + return "MOCK"; } - public void testException() { - try { - db.open(dbFile.getName(), 0); - } catch (Exception e) { - assertNotNull(e); - assertNotNull(e.getMessage()); - } + @Override + public byte[] getEncoded() { + throw new UnsupportedOperationException("not implemented"); } } diff --git a/luni/src/test/java/libcore/javax/crypto/MockKey2.java b/luni/src/test/java/libcore/javax/crypto/MockKey2.java new file mode 100644 index 0000000..44ac0cc --- /dev/null +++ b/luni/src/test/java/libcore/javax/crypto/MockKey2.java @@ -0,0 +1,40 @@ +/* + * Copyright 2013 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.javax.crypto; + +import java.security.Key; + +/** + * A mock Key class used for testing. + */ +@SuppressWarnings("serial") +public class MockKey2 implements Key { + @Override + public String getAlgorithm() { + throw new UnsupportedOperationException("not implemented"); + } + + @Override + public String getFormat() { + return "MOCK"; + } + + @Override + public byte[] getEncoded() { + throw new UnsupportedOperationException("not implemented"); + } +} diff --git a/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParameterGeneratorTestDH.java b/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParameterGeneratorTestDH.java index 578ee6b..e64fb9e 100644 --- a/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParameterGeneratorTestDH.java +++ b/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParameterGeneratorTestDH.java @@ -26,7 +26,7 @@ public class AlgorithmParameterGeneratorTestDH extends super("DH", new AlgorithmParameterKeyAgreementHelper("DH")); } - @BrokenTest("Suffers from DH slowness, disabling for now") + // Broken Test: Suffers from DH slowness, disabling for now public void testAlgorithmParameterGenerator() { super.testAlgorithmParameterGenerator(); } diff --git a/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParametersTestDH.java b/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParametersTestDH.java index 165daa1..897e62b 100644 --- a/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParametersTestDH.java +++ b/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParametersTestDH.java @@ -15,7 +15,6 @@ */ package libcore.javax.crypto.spec; -import dalvik.annotation.BrokenTest; import java.math.BigInteger; import javax.crypto.spec.DHParameterSpec; import tests.security.AlgorithmParameterKeyAgreementHelper; @@ -61,7 +60,7 @@ public class AlgorithmParametersTestDH extends AlgorithmParametersTest { } - @BrokenTest("Suffers from DH slowness, disabling for now") + // Broken Test: Suffers from DH slowness, disabling for now public void testAlgorithmParameters() { super.testAlgorithmParameters(); } diff --git a/luni/src/test/java/libcore/javax/crypto/spec/KeyPairGeneratorTestDH.java b/luni/src/test/java/libcore/javax/crypto/spec/KeyPairGeneratorTestDH.java index c4322ff..8e500e1 100644 --- a/luni/src/test/java/libcore/javax/crypto/spec/KeyPairGeneratorTestDH.java +++ b/luni/src/test/java/libcore/javax/crypto/spec/KeyPairGeneratorTestDH.java @@ -15,7 +15,6 @@ */ package libcore.javax.crypto.spec; -import dalvik.annotation.BrokenTest; import java.security.NoSuchAlgorithmException; import tests.security.KeyAgreementHelper; import tests.security.KeyPairGeneratorTest; @@ -26,7 +25,7 @@ public class KeyPairGeneratorTestDH extends KeyPairGeneratorTest { super("DH", new KeyAgreementHelper("DH")); } - @BrokenTest("Takes ages due to DH computations. Disabling for now.") + // Broken Test: Takes ages due to DH computations. Disabling for now. public void testKeyPairGenerator() throws NoSuchAlgorithmException { super.testKeyPairGenerator(); } diff --git a/luni/src/test/java/libcore/javax/net/ssl/DefaultHostnameVerifierTest.java b/luni/src/test/java/libcore/javax/net/ssl/DefaultHostnameVerifierTest.java index e1c9fe3..feecebe 100644 --- a/luni/src/test/java/libcore/javax/net/ssl/DefaultHostnameVerifierTest.java +++ b/luni/src/test/java/libcore/javax/net/ssl/DefaultHostnameVerifierTest.java @@ -114,15 +114,18 @@ public final class DefaultHostnameVerifierTest extends TestCase { public void testWildcardMatchesWildcardSuffix() { assertTrue(verifier.verifyHostName("b.c.d", "*.b.c.d")); assertTrue(verifier.verifyHostName("imap.google.com", "*.imap.google.com")); + assertFalse(verifier.verifyHostName("imap.google.com.au", "*.imap.google.com")); } public void testWildcardMatchingSubstring() { assertTrue(verifier.verifyHostName("b.c.d", "b*.c.d")); assertTrue(verifier.verifyHostName("imap.google.com", "ima*.google.com")); + assertFalse(verifier.verifyHostName("imap.google.com.au", "ima*.google.com")); } public void testWildcardMatchingEmptySubstring() { assertTrue(verifier.verifyHostName("imap.google.com", "imap*.google.com")); + assertFalse(verifier.verifyHostName("imap.google.com.au", "imap*.google.com")); } public void testWildcardMatchesChildDomain() { diff --git a/luni/src/test/java/libcore/javax/net/ssl/KeyManagerFactoryTest.java b/luni/src/test/java/libcore/javax/net/ssl/KeyManagerFactoryTest.java index f2d36c8..0657f18 100644 --- a/luni/src/test/java/libcore/javax/net/ssl/KeyManagerFactoryTest.java +++ b/luni/src/test/java/libcore/javax/net/ssl/KeyManagerFactoryTest.java @@ -45,8 +45,8 @@ public class KeyManagerFactoryTest extends TestCase { private static TestKeyStore getTestKeyStore() throws Exception { if (TEST_KEY_STORE == null) { TEST_KEY_STORE = new TestKeyStore.Builder() - .keyAlgorithms("RSA", "DSA", "EC", "EC_RSA") - .aliasPrefix("rsa-dsa-ec") + .keyAlgorithms("RSA", "DH_RSA", "DSA", "DH_DSA", "EC", "EC_RSA") + .aliasPrefix("rsa-dsa-ec-dh") .build(); } return TEST_KEY_STORE; diff --git a/luni/src/test/java/libcore/javax/net/ssl/PSKKeyManagerProxy.java b/luni/src/test/java/libcore/javax/net/ssl/PSKKeyManagerProxy.java new file mode 100644 index 0000000..1daa346 --- /dev/null +++ b/luni/src/test/java/libcore/javax/net/ssl/PSKKeyManagerProxy.java @@ -0,0 +1,104 @@ +/* + * Copyright (C) 2014 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.javax.net.ssl; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.net.Socket; +import javax.crypto.SecretKey; +import javax.net.ssl.KeyManager; +import javax.net.ssl.SSLEngine; + +/** + * Reflection-based implementation of {@code PSKKeyManager} from Conscrypt on which these tests + * cannot depend directly. + */ +class PSKKeyManagerProxy implements InvocationHandler { + + static KeyManager getConscryptPSKKeyManager(PSKKeyManagerProxy delegate) { + Class<?> pskKeyManagerInterface; + try { + pskKeyManagerInterface = Class.forName("com.android.org.conscrypt.PSKKeyManager"); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + return (KeyManager) Proxy.newProxyInstance( + PSKKeyManagerProxy.class.getClassLoader(), + new Class[] {pskKeyManagerInterface}, + delegate); + } + + @SuppressWarnings("unused") + protected SecretKey getKey(String identityHint, String identity, Socket socket) { + return null; + } + + @SuppressWarnings("unused") + protected SecretKey getKey(String identityHint, String identity, SSLEngine engine) { + return null; + } + + @SuppressWarnings("unused") + protected String chooseServerKeyIdentityHint(Socket socket) { + return null; + } + + @SuppressWarnings("unused") + protected String chooseServerKeyIdentityHint(SSLEngine engine) { + return null; + } + + @SuppressWarnings("unused") + protected String chooseClientKeyIdentity(String identityHint, Socket socket) { + return null; + } + + @SuppressWarnings("unused") + protected String chooseClientKeyIdentity(String identityHint, SSLEngine engine) { + return null; + } + + @Override + public final Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + String methodName = method.getName(); + Class<?>[] parameterTypes = method.getParameterTypes(); + boolean sslEngineVariant = (parameterTypes.length > 0) + && (SSLEngine.class.equals(parameterTypes[parameterTypes.length - 1])); + if ("getKey".equals(methodName)) { + if (sslEngineVariant) { + return getKey((String) args[0], (String) args[1], (SSLEngine) args[2]); + } else { + return getKey((String) args[0], (String) args[1], (Socket) args[2]); + } + } else if ("chooseServerKeyIdentityHint".equals(methodName)) { + if (sslEngineVariant) { + return chooseServerKeyIdentityHint((SSLEngine) args[0]); + } else { + return chooseServerKeyIdentityHint((Socket) args[0]); + } + } else if ("chooseClientKeyIdentity".equals(methodName)) { + if (sslEngineVariant) { + return chooseClientKeyIdentity((String) args[0], (SSLEngine) args[1]); + } else { + return chooseClientKeyIdentity((String) args[0], (Socket) args[1]); + } + } else { + throw new IllegalArgumentException("Unexpected method: " + method); + } + } +}
\ No newline at end of file diff --git a/luni/src/test/java/libcore/javax/net/ssl/SSLContextTest.java b/luni/src/test/java/libcore/javax/net/ssl/SSLContextTest.java index 900d950..dccadbd 100644 --- a/luni/src/test/java/libcore/javax/net/ssl/SSLContextTest.java +++ b/luni/src/test/java/libcore/javax/net/ssl/SSLContextTest.java @@ -16,17 +16,39 @@ package libcore.javax.net.ssl; +import java.security.InvalidAlgorithmParameterException; import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; import java.security.Provider; +import java.security.Security; +import java.security.UnrecoverableKeyException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Callable; +import libcore.io.IoUtils; import libcore.java.security.StandardNames; import javax.net.ServerSocketFactory; import javax.net.SocketFactory; +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.KeyManagerFactorySpi; +import javax.net.ssl.ManagerFactoryParameters; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; -import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLServerSocket; import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.SSLSessionContext; +import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.TrustManagerFactorySpi; +import javax.net.ssl.X509KeyManager; +import junit.framework.AssertionFailedError; import junit.framework.TestCase; public class SSLContextTest extends TestCase { @@ -59,6 +81,106 @@ public class SSLContextTest extends TestCase { SSLContext.setDefault(defaultContext); } + public void test_SSLContext_defaultConfiguration() throws Exception { + SSLDefaultConfigurationAsserts.assertSSLContext(SSLContext.getDefault()); + + for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) { + SSLContext sslContext = SSLContext.getInstance(protocol); + if (!protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) { + sslContext.init(null, null, null); + } + SSLDefaultConfigurationAsserts.assertSSLContext(sslContext); + } + } + + public void test_SSLContext_pskOnlyConfiguration_defaultProviderOnly() throws Exception { + // Test the scenario where only a PSKKeyManager is provided and no TrustManagers are + // provided. + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init( + new KeyManager[] { + PSKKeyManagerProxy.getConscryptPSKKeyManager(new PSKKeyManagerProxy()) + }, + new TrustManager[0], + null); + List<String> expectedCipherSuites = + new ArrayList<String>(StandardNames.CIPHER_SUITES_DEFAULT_PSK); + expectedCipherSuites.add(StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION); + assertEnabledCipherSuites(expectedCipherSuites, sslContext); + } + + public void test_SSLContext_x509AndPskConfiguration_defaultProviderOnly() throws Exception { + // Test the scenario where an X509TrustManager and PSKKeyManager are provided. + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init( + new KeyManager[] { + PSKKeyManagerProxy.getConscryptPSKKeyManager(new PSKKeyManagerProxy()) + }, + null, // Use default trust managers, one of which is an X.509 one. + null); + List<String> expectedCipherSuites = + new ArrayList<String>(StandardNames.CIPHER_SUITES_DEFAULT_PSK); + expectedCipherSuites.addAll(StandardNames.CIPHER_SUITES_DEFAULT); + assertEnabledCipherSuites(expectedCipherSuites, sslContext); + + // Test the scenario where an X509KeyManager and PSKKeyManager are provided. + sslContext = SSLContext.getInstance("TLS"); + // Just an arbitrary X509KeyManager -- it won't be invoked in this test. + X509KeyManager x509KeyManager = new RandomPrivateKeyX509ExtendedKeyManager(null); + sslContext.init( + new KeyManager[] { + x509KeyManager, + PSKKeyManagerProxy.getConscryptPSKKeyManager(new PSKKeyManagerProxy()) + }, + new TrustManager[0], + null); + assertEnabledCipherSuites(expectedCipherSuites, sslContext); + } + + public void test_SSLContext_emptyConfiguration_defaultProviderOnly() throws Exception { + // Test the scenario where neither X.509 nor PSK KeyManagers or TrustManagers are provided. + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init( + new KeyManager[0], + new TrustManager[0], + null); + assertEnabledCipherSuites( + Arrays.asList(StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION), + sslContext); + } + + private static void assertEnabledCipherSuites( + List<String> expectedCipherSuites, SSLContext sslContext) throws Exception { + assertContentsInOrder( + expectedCipherSuites, sslContext.createSSLEngine().getEnabledCipherSuites()); + assertContentsInOrder( + expectedCipherSuites, + sslContext.createSSLEngine().getSSLParameters().getCipherSuites()); + assertContentsInOrder( + expectedCipherSuites, sslContext.getSocketFactory().getDefaultCipherSuites()); + assertContentsInOrder( + expectedCipherSuites, sslContext.getServerSocketFactory().getDefaultCipherSuites()); + + SSLSocket sslSocket = (SSLSocket) sslContext.getSocketFactory().createSocket(); + try { + assertContentsInOrder( + expectedCipherSuites, sslSocket.getEnabledCipherSuites()); + assertContentsInOrder( + expectedCipherSuites, sslSocket.getSSLParameters().getCipherSuites()); + } finally { + IoUtils.closeQuietly(sslSocket); + } + + SSLServerSocket sslServerSocket = + (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket(); + try { + assertContentsInOrder( + expectedCipherSuites, sslServerSocket.getEnabledCipherSuites()); + } finally { + IoUtils.closeQuietly(sslSocket); + } + } + public void test_SSLContext_getInstance() throws Exception { try { SSLContext.getInstance(null); @@ -109,16 +231,183 @@ public class SSLContextTest extends TestCase { assertEquals(StandardNames.JSSE_PROVIDER_NAME, provider.getName()); } - public void test_SSLContext_init() throws Exception { + public void test_SSLContext_init_Default() throws Exception { + // Assert that initializing a default SSLContext fails because it's supposed to be + // initialized already. + SSLContext sslContext = SSLContext.getInstance(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT); + try { + sslContext.init(null, null, null); + fail(); + } catch (KeyManagementException expected) {} + try { + sslContext.init(new KeyManager[0], new TrustManager[0], null); + fail(); + } catch (KeyManagementException expected) {} + try { + sslContext.init( + new KeyManager[] {new KeyManager() {}}, + new TrustManager[] {new TrustManager() {}}, + null); + fail(); + } catch (KeyManagementException expected) {} + } + + public void test_SSLContext_init_withNullManagerArrays() throws Exception { + // Assert that SSLContext.init works fine even when provided with null arrays of + // KeyManagers and TrustManagers. + // The contract of SSLContext.init is that it will for default X.509 KeyManager and + // TrustManager from the highest priority KeyManagerFactory and TrustManagerFactory. for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) { - SSLContext sslContext = SSLContext.getInstance(protocol); if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) { - try { - sslContext.init(null, null, null); - } catch (KeyManagementException expected) { + // Default SSLContext is provided in an already initialized state + continue; + } + SSLContext sslContext = SSLContext.getInstance(protocol); + sslContext.init(null, null, null); + } + } + + public void test_SSLContext_init_withEmptyManagerArrays() throws Exception { + // Assert that SSLContext.init works fine even when provided with empty arrays of + // KeyManagers and TrustManagers. + // The contract of SSLContext.init is that it will not look for default X.509 KeyManager and + // TrustManager. + // This test thus installs a Provider of KeyManagerFactory and TrustManagerFactory whose + // factories throw exceptions which will make this test fail if the factories are used. + Provider provider = new ThrowExceptionKeyAndTrustManagerFactoryProvider(); + invokeWithHighestPrioritySecurityProvider(provider, new Callable<Void>() { + @Override + public Void call() throws Exception { + assertEquals( + ThrowExceptionKeyAndTrustManagerFactoryProvider.class, + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) + .getProvider().getClass()); + assertEquals( + ThrowExceptionKeyAndTrustManagerFactoryProvider.class, + KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()) + .getProvider().getClass()); + + KeyManager[] keyManagers = new KeyManager[0]; + TrustManager[] trustManagers = new TrustManager[0]; + for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) { + if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) { + // Default SSLContext is provided in an already initialized state + continue; + } + SSLContext sslContext = SSLContext.getInstance(protocol); + sslContext.init(keyManagers, trustManagers, null); } - } else { - sslContext.init(null, null, null); + + return null; + } + }); + } + + public void test_SSLContext_init_withoutX509() throws Exception { + // Assert that SSLContext.init works fine even when provided with KeyManagers and + // TrustManagers which don't include the X.509 ones. + // The contract of SSLContext.init is that it will not look for default X.509 KeyManager and + // TrustManager. + // This test thus installs a Provider of KeyManagerFactory and TrustManagerFactory whose + // factories throw exceptions which will make this test fail if the factories are used. + Provider provider = new ThrowExceptionKeyAndTrustManagerFactoryProvider(); + invokeWithHighestPrioritySecurityProvider(provider, new Callable<Void>() { + @Override + public Void call() throws Exception { + assertEquals( + ThrowExceptionKeyAndTrustManagerFactoryProvider.class, + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) + .getProvider().getClass()); + assertEquals( + ThrowExceptionKeyAndTrustManagerFactoryProvider.class, + KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()) + .getProvider().getClass()); + + KeyManager[] keyManagers = new KeyManager[] {new KeyManager() {}}; + TrustManager[] trustManagers = new TrustManager[] {new TrustManager() {}}; + for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) { + if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) { + // Default SSLContext is provided in an already initialized state + continue; + } + SSLContext sslContext = SSLContext.getInstance(protocol); + sslContext.init(keyManagers, trustManagers, null); + } + + return null; + } + }); + } + + public static class ThrowExceptionKeyAndTrustManagerFactoryProvider extends Provider { + public ThrowExceptionKeyAndTrustManagerFactoryProvider() { + super("ThrowExceptionKeyAndTrustManagerProvider", + 1.0, + "SSLContextTest fake KeyManagerFactory and TrustManagerFactory provider"); + + put("TrustManagerFactory." + TrustManagerFactory.getDefaultAlgorithm(), + ThrowExceptionTrustManagagerFactorySpi.class.getName()); + put("TrustManagerFactory.PKIX", ThrowExceptionTrustManagagerFactorySpi.class.getName()); + + put("KeyManagerFactory." + KeyManagerFactory.getDefaultAlgorithm(), + ThrowExceptionKeyManagagerFactorySpi.class.getName()); + put("KeyManagerFactory.PKIX", ThrowExceptionKeyManagagerFactorySpi.class.getName()); + } + } + + public static class ThrowExceptionTrustManagagerFactorySpi extends TrustManagerFactorySpi { + @Override + protected void engineInit(KeyStore ks) throws KeyStoreException { + fail(); + } + + @Override + protected void engineInit(ManagerFactoryParameters spec) + throws InvalidAlgorithmParameterException { + fail(); + } + + @Override + protected TrustManager[] engineGetTrustManagers() { + throw new AssertionFailedError(); + } + } + + public static class ThrowExceptionKeyManagagerFactorySpi extends KeyManagerFactorySpi { + @Override + protected void engineInit(KeyStore ks, char[] password) throws KeyStoreException, + NoSuchAlgorithmException, UnrecoverableKeyException { + fail(); + } + + @Override + protected void engineInit(ManagerFactoryParameters spec) + throws InvalidAlgorithmParameterException { + fail(); + } + + @Override + protected KeyManager[] engineGetKeyManagers() { + throw new AssertionFailedError(); + } + } + + /** + * Installs the specified security provider as the highest provider, invokes the provided + * {@link Callable}, and removes the provider. + * + * @return result returned by the {@code callable}. + */ + private static <T> T invokeWithHighestPrioritySecurityProvider( + Provider provider, Callable<T> callable) throws Exception { + int providerPosition = -1; + try { + providerPosition = Security.insertProviderAt(provider, 1); + assertEquals(1, providerPosition); + return callable.call(); + } finally { + if (providerPosition != -1) { + Security.removeProvider(provider.getName()); } } } @@ -244,53 +533,6 @@ public class SSLContextTest extends TestCase { } } - public void test_SSLContext_getDefaultSSLParameters() throws Exception { - for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) { - SSLContext sslContext = SSLContext.getInstance(protocol); - if (!protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) { - sslContext.init(null, null, null); - } - - SSLParameters p = sslContext.getDefaultSSLParameters(); - assertNotNull(p); - - String[] cipherSuites = p.getCipherSuites(); - assertNotNull(cipherSuites); - StandardNames.assertValidCipherSuites(StandardNames.CIPHER_SUITES, cipherSuites); - - String[] protocols = p.getProtocols(); - assertNotNull(protocols); - StandardNames.assertValidCipherSuites(StandardNames.SSL_SOCKET_PROTOCOLS, protocols); - - assertFalse(p.getWantClientAuth()); - assertFalse(p.getNeedClientAuth()); - } - } - - public void test_SSLContext_getSupportedSSLParameters() throws Exception { - for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) { - SSLContext sslContext = SSLContext.getInstance(protocol); - if (!protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) { - sslContext.init(null, null, null); - } - - SSLParameters p = sslContext.getSupportedSSLParameters(); - assertNotNull(p); - - String[] cipherSuites = p.getCipherSuites(); - assertNotNull(cipherSuites); - StandardNames.assertSupportedCipherSuites(StandardNames.CIPHER_SUITES, cipherSuites); - - String[] protocols = p.getProtocols(); - assertNotNull(protocols); - StandardNames.assertSupportedProtocols(StandardNames.SSL_SOCKET_PROTOCOLS, - protocols); - - assertFalse(p.getWantClientAuth()); - assertFalse(p.getNeedClientAuth()); - } - } - public void test_SSLContextTest_TestSSLContext_create() { TestSSLContext testContext = TestSSLContext.create(); assertNotNull(testContext); @@ -298,8 +540,16 @@ public class SSLContextTest extends TestCase { assertNull(testContext.clientStorePassword); assertNotNull(testContext.serverKeyStore); assertEquals(StandardNames.IS_RI, testContext.serverStorePassword != null); - assertNotNull(testContext.clientKeyManager); - assertNotNull(testContext.serverKeyManager); + assertNotNull(testContext.clientKeyManagers); + assertNotNull(testContext.serverKeyManagers); + if (testContext.clientKeyManagers.length == 0) { + fail("No client KeyManagers"); + } + if (testContext.serverKeyManagers.length == 0) { + fail("No server KeyManagers"); + } + assertNotNull(testContext.clientKeyManagers[0]); + assertNotNull(testContext.serverKeyManagers[0]); assertNotNull(testContext.clientTrustManager); assertNotNull(testContext.serverTrustManager); assertNotNull(testContext.clientContext); @@ -309,4 +559,16 @@ public class SSLContextTest extends TestCase { assertTrue(testContext.port != 0); testContext.close(); } + + private static void assertContentsInOrder(List<String> expected, String... actual) { + if (expected.size() != actual.length) { + fail("Unexpected length. Expected len <" + expected.size() + + ">, actual len <" + actual.length + ">, expected <" + expected + + ">, actual <" + Arrays.asList(actual) + ">"); + } + if (!expected.equals(Arrays.asList(actual))) { + fail("Unexpected element(s). Expected <" + expected + + ">, actual <" + Arrays.asList(actual) + ">" ); + } + } } diff --git a/luni/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java b/luni/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java index 33a8923..fb7e0c9 100644 --- a/luni/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java +++ b/luni/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java @@ -17,15 +17,20 @@ package libcore.javax.net.ssl; import java.io.IOException; +import java.nio.ByteBuffer; import java.util.Arrays; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLEngineResult.HandshakeStatus; import javax.net.ssl.SSLException; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSession; +import javax.net.ssl.X509ExtendedKeyManager; import junit.framework.TestCase; import libcore.java.security.StandardNames; import libcore.java.security.TestKeyStore; @@ -59,13 +64,15 @@ public class SSLEngineTest extends TestCase { && !b.isOutboundDone()); } - public void test_SSLEngine_getSupportedCipherSuites_names() throws Exception { + public void test_SSLEngine_defaultConfiguration() throws Exception { + SSLDefaultConfigurationAsserts.assertSSLEngine( + TestSSLContext.create().clientContext.createSSLEngine()); + } + + public void test_SSLEngine_getSupportedCipherSuites_returnsCopies() throws Exception { TestSSLContext c = TestSSLContext.create(); SSLEngine e = c.clientContext.createSSLEngine(); - String[] cipherSuites = e.getSupportedCipherSuites(); - StandardNames.assertSupportedCipherSuites(StandardNames.CIPHER_SUITES_SSLENGINE, - cipherSuites); - assertNotSame(cipherSuites, e.getSupportedCipherSuites()); + assertNotSame(e.getSupportedCipherSuites(), e.getSupportedCipherSuites()); c.close(); } @@ -77,105 +84,214 @@ public class SSLEngineTest extends TestCase { .ca(true) .build(); test_SSLEngine_getSupportedCipherSuites_connect(testKeyStore, false); - if (StandardNames.IS_RI) { - test_SSLEngine_getSupportedCipherSuites_connect(testKeyStore, true); - } + test_SSLEngine_getSupportedCipherSuites_connect(testKeyStore, true); } private void test_SSLEngine_getSupportedCipherSuites_connect(TestKeyStore testKeyStore, boolean secureRenegotiation) throws Exception { - TestSSLContext c = TestSSLContext.create(testKeyStore, testKeyStore); + KeyManager pskKeyManager = PSKKeyManagerProxy.getConscryptPSKKeyManager( + new PSKKeyManagerProxy() { + @Override + protected SecretKey getKey(String identityHint, String identity, SSLEngine engine) { + return new SecretKeySpec("Just an arbitrary key".getBytes(), "RAW"); + } + }); + TestSSLContext c = TestSSLContext.createWithAdditionalKeyManagers( + testKeyStore, testKeyStore, + new KeyManager[] {pskKeyManager}, new KeyManager[] {pskKeyManager}); // Create a TestSSLContext where the KeyManager returns wrong (randomly generated) private // keys, matching the algorithm and parameters of the correct keys. // I couldn't find a more elegant way to achieve this other than temporarily replacing the - // first element of TestKeyStore.keyManagers while invoking TestSSLContext.create. + // first X509ExtendedKeyManager element of TestKeyStore.keyManagers while invoking + // TestSSLContext.create. TestSSLContext cWithWrongPrivateKeys; { - KeyManager originalKeyManager = testKeyStore.keyManagers[0]; - testKeyStore.keyManagers[0] = - new RandomPrivateKeyX509ExtendedKeyManager(c.serverKeyManager); + // Create a RandomPrivateKeyX509ExtendedKeyManager based on the first + // X509ExtendedKeyManager in c.serverKeyManagers. + KeyManager randomPrivateKeyX509ExtendedKeyManager = null; + for (KeyManager keyManager : c.serverKeyManagers) { + if (keyManager instanceof X509ExtendedKeyManager) { + randomPrivateKeyX509ExtendedKeyManager = + new RandomPrivateKeyX509ExtendedKeyManager((X509ExtendedKeyManager) keyManager); + break; + } + } + if (randomPrivateKeyX509ExtendedKeyManager == null) { + fail("No X509ExtendedKeyManager in c.serverKeyManagers"); + } + + // Find the first X509ExtendedKeyManager in testKeyStore.keyManagers + int replaceIndex = -1; + for (int i = 0; i < testKeyStore.keyManagers.length; i++) { + KeyManager keyManager = testKeyStore.keyManagers[i]; + if (keyManager instanceof X509ExtendedKeyManager) { + replaceIndex = i; + break; + } + } + if (replaceIndex == -1) { + fail("No X509ExtendedKeyManager in testKeyStore.keyManagers"); + } + + // Temporarily substitute the RandomPrivateKeyX509ExtendedKeyManager in place of the + // original X509ExtendedKeyManager. + KeyManager originalKeyManager = testKeyStore.keyManagers[replaceIndex]; + testKeyStore.keyManagers[replaceIndex] = randomPrivateKeyX509ExtendedKeyManager; cWithWrongPrivateKeys = TestSSLContext.create(testKeyStore, testKeyStore); - testKeyStore.keyManagers[0] = originalKeyManager; + testKeyStore.keyManagers[replaceIndex] = originalKeyManager; } + // To catch all the errors. + StringBuilder error = new StringBuilder(); + String[] cipherSuites = c.clientContext.createSSLEngine().getSupportedCipherSuites(); for (String cipherSuite : cipherSuites) { - boolean errorExpected = StandardNames.IS_RI && cipherSuite.endsWith("_SHA256"); try { - /* - * TLS_EMPTY_RENEGOTIATION_INFO_SCSV cannot be used on - * its own, but instead in conjunction with other - * cipher suites. - */ - if (cipherSuite.equals(StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION) - || cipherSuite.equals(StandardNames.CIPHER_SUITE_FALLBACK)) { - continue; - } - /* - * Kerberos cipher suites require external setup. See "Kerberos Requirements" in - * https://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/JSSERefGuide.html - * #KRBRequire - */ - if (cipherSuite.startsWith("TLS_KRB5_")) { - continue; - } + // Skip cipher suites that are obsoleted. + if (StandardNames.IS_RI && "TLSv1.2".equals(c.clientContext.getProtocol()) + && StandardNames.CIPHER_SUITES_OBSOLETE_TLS12.contains(cipherSuite)) { + continue; + } + /* + * Signaling Cipher Suite Values (SCSV) cannot be used on their own, but instead in + * conjunction with other cipher suites. + */ + if (cipherSuite.equals(StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION) + || cipherSuite.equals(StandardNames.CIPHER_SUITE_FALLBACK)) { + continue; + } + /* + * Kerberos cipher suites require external setup. See "Kerberos Requirements" in + * https://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/JSSERefGuide.html + * #KRBRequire + */ + if (cipherSuite.startsWith("TLS_KRB5_")) { + continue; + } - final String[] cipherSuiteArray - = (secureRenegotiation - ? new String[] { cipherSuite, - StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION } - : new String[] { cipherSuite }); + final String[] cipherSuiteArray + = (secureRenegotiation + ? new String[] { cipherSuite, + StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION } + : new String[] { cipherSuite }); - // Check that handshake succeeds. - assertConnected(TestSSLEnginePair.create(c, new TestSSLEnginePair.Hooks() { + // Check that handshake succeeds. + TestSSLEnginePair pair = TestSSLEnginePair.create(c, new TestSSLEnginePair.Hooks() { + @Override + void beforeBeginHandshake(SSLEngine client, SSLEngine server) { + client.setEnabledCipherSuites(cipherSuiteArray); + server.setEnabledCipherSuites(cipherSuiteArray); + } + }); + assertConnected(pair); + + boolean needsRecordSplit = + ("TLS".equalsIgnoreCase(c.clientContext.getProtocol()) + || "SSLv3".equalsIgnoreCase(c.clientContext.getProtocol())) + && cipherSuite.contains("_CBC_"); + + assertSendsCorrectly("This is the client. Hello!".getBytes(), + pair.client, pair.server, needsRecordSplit); + assertSendsCorrectly("This is the server. Hi!".getBytes(), + pair.server, pair.client, needsRecordSplit); + + // Check that handshake fails when the server does not possess the private key + // corresponding to the server's certificate. This is achieved by using SSLContext + // cWithWrongPrivateKeys whose KeyManager returns wrong private keys that match + // the algorithm (and parameters) of the correct keys. + boolean serverAuthenticatedUsingPublicKey = true; + if (cipherSuite.contains("_anon_")) { + serverAuthenticatedUsingPublicKey = false; + } else if ((cipherSuite.startsWith("TLS_PSK_")) + || (cipherSuite.startsWith("TLS_ECDHE_PSK_"))) { + serverAuthenticatedUsingPublicKey = false; + } + if (serverAuthenticatedUsingPublicKey) { + try { + TestSSLEnginePair p = TestSSLEnginePair.create( + cWithWrongPrivateKeys, new TestSSLEnginePair.Hooks() { @Override void beforeBeginHandshake(SSLEngine client, SSLEngine server) { client.setEnabledCipherSuites(cipherSuiteArray); server.setEnabledCipherSuites(cipherSuiteArray); } - })); - assertFalse(errorExpected); - - // Check that handshake fails when the server does not possess the private key - // corresponding to the server's certificate. This is achieved by using SSLContext - // cWithWrongPrivateKeys whose KeyManager returns wrong private keys that match - // the algorithm (and parameters) of the correct keys. - if (!cipherSuite.contains("_anon_")) { - // The identity of the server is verified only in non-anonymous key exchanges. - try { - TestSSLEnginePair p = TestSSLEnginePair.create( - cWithWrongPrivateKeys, new TestSSLEnginePair.Hooks() { - @Override - void beforeBeginHandshake(SSLEngine client, SSLEngine server) { - client.setEnabledCipherSuites(cipherSuiteArray); - server.setEnabledCipherSuites(cipherSuiteArray); - } - }); - assertConnected(p); - fail("Handshake succeeded for " + cipherSuite - + " despite server not having the correct private key"); - } catch (IOException expected) {} - } - } catch (Exception maybeExpected) { - if (!errorExpected) { - throw new Exception("Problem trying to connect cipher suite " + cipherSuite, - maybeExpected); - } + }); + assertNotConnected(p); + } catch (IOException expected) {} + } + } catch (Exception e) { + String message = ("Problem trying to connect cipher suite " + cipherSuite); + System.out.println(message); + e.printStackTrace(); + error.append(message); + error.append('\n'); } } c.close(); + + if (error.length() > 0) { + throw new Exception("One or more problems in " + + "test_SSLEngine_getSupportedCipherSuites_connect:\n" + error); + } + } + + private static void assertSendsCorrectly(final byte[] sourceBytes, SSLEngine source, + SSLEngine dest, boolean needsRecordSplit) throws SSLException { + ByteBuffer sourceOut = ByteBuffer.wrap(sourceBytes); + SSLSession sourceSession = source.getSession(); + ByteBuffer sourceToDest = ByteBuffer.allocate(sourceSession.getPacketBufferSize()); + SSLEngineResult sourceOutRes = source.wrap(sourceOut, sourceToDest); + sourceToDest.flip(); + + String sourceCipherSuite = source.getSession().getCipherSuite(); + assertEquals(sourceCipherSuite, sourceBytes.length, sourceOutRes.bytesConsumed()); + assertEquals(sourceCipherSuite, HandshakeStatus.NOT_HANDSHAKING, + sourceOutRes.getHandshakeStatus()); + + SSLSession destSession = dest.getSession(); + ByteBuffer destIn = ByteBuffer.allocate(destSession.getApplicationBufferSize()); + + int numUnwrapCalls = 0; + while (destIn.position() != sourceOut.limit()) { + SSLEngineResult destRes = dest.unwrap(sourceToDest, destIn); + assertEquals(sourceCipherSuite, HandshakeStatus.NOT_HANDSHAKING, + destRes.getHandshakeStatus()); + if (needsRecordSplit && numUnwrapCalls == 0) { + assertEquals(sourceCipherSuite, 1, destRes.bytesProduced()); + } + numUnwrapCalls++; + } + + destIn.flip(); + byte[] actual = new byte[destIn.remaining()]; + destIn.get(actual); + assertEquals(sourceCipherSuite, Arrays.toString(sourceBytes), Arrays.toString(actual)); + + if (needsRecordSplit) { + assertEquals(sourceCipherSuite, 2, numUnwrapCalls); + } else { + assertEquals(sourceCipherSuite, 1, numUnwrapCalls); + } } - public void test_SSLEngine_getEnabledCipherSuites() throws Exception { + public void test_SSLEngine_getEnabledCipherSuites_returnsCopies() throws Exception { TestSSLContext c = TestSSLContext.create(); SSLEngine e = c.clientContext.createSSLEngine(); - String[] cipherSuites = e.getEnabledCipherSuites(); - StandardNames.assertValidCipherSuites(StandardNames.CIPHER_SUITES, cipherSuites); - assertNotSame(cipherSuites, e.getEnabledCipherSuites()); + assertNotSame(e.getEnabledCipherSuites(), e.getEnabledCipherSuites()); c.close(); } + public void test_SSLEngine_setEnabledCipherSuites_storesCopy() throws Exception { + TestSSLContext c = TestSSLContext.create(); + SSLEngine e = c.clientContext.createSSLEngine(); + String[] array = new String[] {e.getEnabledCipherSuites()[0]}; + String originalFirstElement = array[0]; + e.setEnabledCipherSuites(array); + array[0] = "Modified after having been set"; + assertEquals(originalFirstElement, e.getEnabledCipherSuites()[0]); + } + public void test_SSLEngine_setEnabledCipherSuites() throws Exception { TestSSLContext c = TestSSLContext.create(); SSLEngine e = c.clientContext.createSSLEngine(); @@ -199,28 +315,39 @@ public class SSLEngineTest extends TestCase { e.setEnabledCipherSuites(new String[0]); e.setEnabledCipherSuites(e.getEnabledCipherSuites()); e.setEnabledCipherSuites(e.getSupportedCipherSuites()); + + // Check that setEnabledCipherSuites affects getEnabledCipherSuites + String[] cipherSuites = new String[] { e.getSupportedCipherSuites()[0] }; + e.setEnabledCipherSuites(cipherSuites); + assertEquals(Arrays.asList(cipherSuites), Arrays.asList(e.getEnabledCipherSuites())); + c.close(); } - public void test_SSLEngine_getSupportedProtocols() throws Exception { + public void test_SSLEngine_getSupportedProtocols_returnsCopies() throws Exception { TestSSLContext c = TestSSLContext.create(); SSLEngine e = c.clientContext.createSSLEngine(); - String[] protocols = e.getSupportedProtocols(); - StandardNames.assertSupportedProtocols(StandardNames.SSL_SOCKET_PROTOCOLS_SSLENGINE, - protocols); - assertNotSame(protocols, e.getSupportedProtocols()); + assertNotSame(e.getSupportedProtocols(), e.getSupportedProtocols()); c.close(); } - public void test_SSLEngine_getEnabledProtocols() throws Exception { + public void test_SSLEngine_getEnabledProtocols_returnsCopies() throws Exception { TestSSLContext c = TestSSLContext.create(); SSLEngine e = c.clientContext.createSSLEngine(); - String[] protocols = e.getEnabledProtocols(); - StandardNames.assertValidProtocols(StandardNames.SSL_SOCKET_PROTOCOLS, protocols); - assertNotSame(protocols, e.getEnabledProtocols()); + assertNotSame(e.getEnabledProtocols(), e.getEnabledProtocols()); c.close(); } + public void test_SSLEngine_setEnabledProtocols_storesCopy() throws Exception { + TestSSLContext c = TestSSLContext.create(); + SSLEngine e = c.clientContext.createSSLEngine(); + String[] array = new String[] {e.getEnabledProtocols()[0]}; + String originalFirstElement = array[0]; + e.setEnabledProtocols(array); + array[0] = "Modified after having been set"; + assertEquals(originalFirstElement, e.getEnabledProtocols()[0]); + } + public void test_SSLEngine_setEnabledProtocols() throws Exception { TestSSLContext c = TestSSLContext.create(); SSLEngine e = c.clientContext.createSSLEngine(); @@ -243,6 +370,22 @@ public class SSLEngineTest extends TestCase { e.setEnabledProtocols(new String[0]); e.setEnabledProtocols(e.getEnabledProtocols()); e.setEnabledProtocols(e.getSupportedProtocols()); + + // Check that setEnabledProtocols affects getEnabledProtocols + for (String protocol : e.getSupportedProtocols()) { + if ("SSLv2Hello".equals(protocol)) { + try { + e.setEnabledProtocols(new String[] { protocol }); + fail("Should fail when SSLv2Hello is set by itself"); + } catch (IllegalArgumentException expected) {} + } else { + String[] protocols = new String[] { protocol }; + e.setEnabledProtocols(protocols); + assertEquals(Arrays.deepToString(protocols), + Arrays.deepToString(e.getEnabledProtocols())); + } + } + c.close(); } @@ -297,17 +440,34 @@ public class SSLEngineTest extends TestCase { } public void test_SSLEngine_setUseClientMode() throws Exception { + boolean[] finished; + // client is client, server is server - assertConnected(test_SSLEngine_setUseClientMode(true, false)); + finished = new boolean[2]; + assertConnected(test_SSLEngine_setUseClientMode(true, false, finished)); + assertTrue(finished[0]); + assertTrue(finished[1]); // client is server, server is client - assertConnected(test_SSLEngine_setUseClientMode(false, true)); + finished = new boolean[2]; + assertConnected(test_SSLEngine_setUseClientMode(false, true, finished)); + assertTrue(finished[0]); + assertTrue(finished[1]); // both are client - assertNotConnected(test_SSLEngine_setUseClientMode(true, true)); + /* + * Our implementation throws an SSLHandshakeException, but RI just + * stalls forever + */ + try { + assertNotConnected(test_SSLEngine_setUseClientMode(true, true, null)); + assertTrue(StandardNames.IS_RI); + } catch (SSLHandshakeException maybeExpected) { + assertFalse(StandardNames.IS_RI); + } // both are server - assertNotConnected(test_SSLEngine_setUseClientMode(false, false)); + assertNotConnected(test_SSLEngine_setUseClientMode(false, false, null)); } public void test_SSLEngine_setUseClientMode_afterHandshake() throws Exception { @@ -327,7 +487,8 @@ public class SSLEngineTest extends TestCase { } private TestSSLEnginePair test_SSLEngine_setUseClientMode(final boolean clientClientMode, - final boolean serverClientMode) + final boolean serverClientMode, + final boolean[] finished) throws Exception { TestSSLContext c; if (!clientClientMode && serverClientMode) { @@ -342,7 +503,7 @@ public class SSLEngineTest extends TestCase { client.setUseClientMode(clientClientMode); server.setUseClientMode(serverClientMode); } - }); + }, finished); } public void test_SSLEngine_clientAuth() throws Exception { @@ -440,13 +601,19 @@ public class SSLEngineTest extends TestCase { } public void test_SSLEngine_setEnableSessionCreation_server() throws Exception { - TestSSLEnginePair p = TestSSLEnginePair.create(new TestSSLEnginePair.Hooks() { - @Override - void beforeBeginHandshake(SSLEngine client, SSLEngine server) { - server.setEnableSessionCreation(false); - } - }); - assertNotConnected(p); + try { + TestSSLEnginePair p = TestSSLEnginePair.create(new TestSSLEnginePair.Hooks() { + @Override + void beforeBeginHandshake(SSLEngine client, SSLEngine server) { + server.setEnableSessionCreation(false); + } + }); + // For some reason, the RI doesn't throw an SSLException. + assertTrue(StandardNames.IS_RI); + assertNotConnected(p); + } catch (SSLException maybeExpected) { + assertFalse(StandardNames.IS_RI); + } } public void test_SSLEngine_setEnableSessionCreation_client() throws Exception { @@ -470,12 +637,10 @@ public class SSLEngineTest extends TestCase { assertNotNull(p); String[] cipherSuites = p.getCipherSuites(); - StandardNames.assertValidCipherSuites(StandardNames.CIPHER_SUITES, cipherSuites); assertNotSame(cipherSuites, e.getEnabledCipherSuites()); assertEquals(Arrays.asList(cipherSuites), Arrays.asList(e.getEnabledCipherSuites())); String[] protocols = p.getProtocols(); - StandardNames.assertValidProtocols(StandardNames.SSL_SOCKET_PROTOCOLS, protocols); assertNotSame(protocols, e.getEnabledProtocols()); assertEquals(Arrays.asList(protocols), Arrays.asList(e.getEnabledProtocols())); diff --git a/luni/src/test/java/libcore/javax/net/ssl/SSLServerSocketFactoryTest.java b/luni/src/test/java/libcore/javax/net/ssl/SSLServerSocketFactoryTest.java new file mode 100644 index 0000000..ea9c3f0 --- /dev/null +++ b/luni/src/test/java/libcore/javax/net/ssl/SSLServerSocketFactoryTest.java @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2013 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.javax.net.ssl; + +import javax.net.ssl.SSLServerSocketFactory; +import junit.framework.TestCase; + +public class SSLServerSocketFactoryTest extends TestCase { + + public void testDefaultConfiguration() throws Exception { + SSLDefaultConfigurationAsserts.assertSSLServerSocketFactory( + (SSLServerSocketFactory) SSLServerSocketFactory.getDefault()); + } +} diff --git a/luni/src/test/java/libcore/javax/net/ssl/SSLServerSocketTest.java b/luni/src/test/java/libcore/javax/net/ssl/SSLServerSocketTest.java new file mode 100644 index 0000000..59c44c1 --- /dev/null +++ b/luni/src/test/java/libcore/javax/net/ssl/SSLServerSocketTest.java @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2013 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.javax.net.ssl; + +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLServerSocketFactory; +import junit.framework.TestCase; +import java.util.Arrays; + +public class SSLServerSocketTest extends TestCase { + + public void testDefaultConfiguration() throws Exception { + SSLDefaultConfigurationAsserts.assertSSLServerSocket( + (SSLServerSocket) SSLServerSocketFactory.getDefault().createServerSocket()); + } + + public void testSetEnabledCipherSuitesAffectsGetter() throws Exception { + SSLServerSocket socket = + (SSLServerSocket) SSLServerSocketFactory.getDefault().createServerSocket(); + String[] cipherSuites = new String[] {socket.getSupportedCipherSuites()[0]}; + socket.setEnabledCipherSuites(cipherSuites); + assertEquals(Arrays.asList(cipherSuites), Arrays.asList(socket.getEnabledCipherSuites())); + } + + public void testSetEnabledCipherSuitesStoresCopy() throws Exception { + SSLServerSocket socket = + (SSLServerSocket) SSLServerSocketFactory.getDefault().createServerSocket(); + String[] array = new String[] {socket.getEnabledCipherSuites()[0]}; + String originalFirstElement = array[0]; + socket.setEnabledCipherSuites(array); + array[0] = "Modified after having been set"; + assertEquals(originalFirstElement, socket.getEnabledCipherSuites()[0]); + } + + public void testSetEnabledProtocolsAffectsGetter() throws Exception { + SSLServerSocket socket = + (SSLServerSocket) SSLServerSocketFactory.getDefault().createServerSocket(); + String[] protocols = new String[] {socket.getSupportedProtocols()[0]}; + socket.setEnabledProtocols(protocols); + assertEquals(Arrays.asList(protocols), Arrays.asList(socket.getEnabledProtocols())); + } + + public void testSetEnabledProtocolsStoresCopy() throws Exception { + SSLServerSocket socket = + (SSLServerSocket) SSLServerSocketFactory.getDefault().createServerSocket(); + String[] array = new String[] {socket.getEnabledProtocols()[0]}; + String originalFirstElement = array[0]; + socket.setEnabledProtocols(array); + array[0] = "Modified after having been set"; + assertEquals(originalFirstElement, socket.getEnabledProtocols()[0]); + } +} diff --git a/luni/src/test/java/libcore/javax/net/ssl/SSLSessionTest.java b/luni/src/test/java/libcore/javax/net/ssl/SSLSessionTest.java index ba048a8..a434d94 100644 --- a/luni/src/test/java/libcore/javax/net/ssl/SSLSessionTest.java +++ b/luni/src/test/java/libcore/javax/net/ssl/SSLSessionTest.java @@ -49,7 +49,7 @@ public class SSLSessionTest extends TestCase { assertNotNull(s.client.getCipherSuite()); assertEquals(s.server.getCipherSuite(), s.client.getCipherSuite()); - assertTrue(StandardNames.CIPHER_SUITES.contains(s.server.getCipherSuite())); + StandardNames.assertValidCipherSuites(new String[] {s.server.getCipherSuite()}); s.close(); } diff --git a/luni/src/test/java/libcore/javax/net/ssl/SSLSocketFactoryTest.java b/luni/src/test/java/libcore/javax/net/ssl/SSLSocketFactoryTest.java index 14a54fd..acf69c0 100644 --- a/luni/src/test/java/libcore/javax/net/ssl/SSLSocketFactoryTest.java +++ b/luni/src/test/java/libcore/javax/net/ssl/SSLSocketFactoryTest.java @@ -16,37 +16,212 @@ package libcore.javax.net.ssl; +import java.lang.reflect.Field; +import java.lang.reflect.Method; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; -import libcore.java.security.StandardNames; +import java.security.KeyManagementException; +import java.security.Provider; +import java.security.SecureRandom; +import java.security.Security; +import java.util.Properties; import javax.net.ServerSocketFactory; import javax.net.SocketFactory; +import javax.net.ssl.KeyManager; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLContextSpi; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLServerSocketFactory; +import javax.net.ssl.SSLSessionContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; import junit.framework.TestCase; +import libcore.java.security.StandardNames; public class SSLSocketFactoryTest extends TestCase { + private static final String SSL_PROPERTY = "ssl.SocketFactory.provider"; + public void test_SSLSocketFactory_getDefault() { SocketFactory sf = SSLSocketFactory.getDefault(); assertNotNull(sf); assertTrue(SSLSocketFactory.class.isAssignableFrom(sf.getClass())); } - public void test_SSLSocketFactory_getDefaultCipherSuites() { + public static class FakeSSLSocketProvider extends Provider { + public FakeSSLSocketProvider() { + super("FakeSSLSocketProvider", 1.0, "Testing provider"); + put("SSLContext.Default", FakeSSLContextSpi.class.getName()); + } + } + + public static final class FakeSSLContextSpi extends SSLContextSpi { + @Override + protected void engineInit(KeyManager[] keyManagers, TrustManager[] trustManagers, + SecureRandom secureRandom) throws KeyManagementException { + throw new UnsupportedOperationException(); + } + + @Override + protected SSLSocketFactory engineGetSocketFactory() { + return new FakeSSLSocketFactory(); + } + + @Override + protected SSLServerSocketFactory engineGetServerSocketFactory() { + throw new UnsupportedOperationException(); + } + + @Override + protected SSLEngine engineCreateSSLEngine(String s, int i) { + throw new UnsupportedOperationException(); + } + + @Override + protected SSLEngine engineCreateSSLEngine() { + throw new UnsupportedOperationException(); + } + + @Override + protected SSLSessionContext engineGetServerSessionContext() { + throw new UnsupportedOperationException(); + } + + @Override + protected SSLSessionContext engineGetClientSessionContext() { + throw new UnsupportedOperationException(); + } + } + + public static class FakeSSLSocketFactory extends SSLSocketFactory { + public FakeSSLSocketFactory() { + } + + @Override + public String[] getDefaultCipherSuites() { + throw new UnsupportedOperationException(); + } + + @Override + public String[] getSupportedCipherSuites() { + throw new UnsupportedOperationException(); + } + + @Override + public Socket createSocket(Socket s, String host, int port, boolean autoClose) { + throw new UnsupportedOperationException(); + } + + @Override + public Socket createSocket(InetAddress address, int port, InetAddress localAddress, + int localPort) { + throw new UnsupportedOperationException(); + } + + @Override + public Socket createSocket(InetAddress host, int port) { + throw new UnsupportedOperationException(); + } + + @Override + public Socket createSocket(String host, int port, InetAddress localHost, int localPort) { + throw new UnsupportedOperationException(); + } + + @Override + public Socket createSocket(String host, int port) { + throw new UnsupportedOperationException(); + } + } + + public void test_SSLSocketFactory_getDefault_cacheInvalidate() throws Exception { + String origProvider = resetSslProvider(); + try { + SocketFactory sf1 = SSLSocketFactory.getDefault(); + assertNotNull(sf1); + assertTrue(SSLSocketFactory.class.isAssignableFrom(sf1.getClass())); + + Provider fakeProvider = new FakeSSLSocketProvider(); + SocketFactory sf4 = null; + SSLContext origContext = null; + try { + origContext = SSLContext.getDefault(); + Security.insertProviderAt(fakeProvider, 1); + SSLContext.setDefault(SSLContext.getInstance("Default", fakeProvider)); + + sf4 = SSLSocketFactory.getDefault(); + assertNotNull(sf4); + assertTrue(SSLSocketFactory.class.isAssignableFrom(sf4.getClass())); + + assertFalse(sf1.getClass() + " should not be " + sf4.getClass(), + sf1.getClass().equals(sf4.getClass())); + } finally { + SSLContext.setDefault(origContext); + Security.removeProvider(fakeProvider.getName()); + } + + SocketFactory sf3 = SSLSocketFactory.getDefault(); + assertNotNull(sf3); + assertTrue(SSLSocketFactory.class.isAssignableFrom(sf3.getClass())); + + assertTrue(sf1.getClass() + " should be " + sf3.getClass(), + sf1.getClass().equals(sf3.getClass())); + + if (!StandardNames.IS_RI) { + Security.setProperty(SSL_PROPERTY, FakeSSLSocketFactory.class.getName()); + SocketFactory sf2 = SSLSocketFactory.getDefault(); + assertNotNull(sf2); + assertTrue(SSLSocketFactory.class.isAssignableFrom(sf2.getClass())); + + assertFalse(sf2.getClass().getName() + " should not be " + Security.getProperty(SSL_PROPERTY), + sf1.getClass().equals(sf2.getClass())); + assertTrue(sf2.getClass().equals(sf4.getClass())); + + resetSslProvider(); + } + } finally { + Security.setProperty(SSL_PROPERTY, origProvider); + } + } + + private String resetSslProvider() { + String origProvider = Security.getProperty(SSL_PROPERTY); + + try { + Field field_secprops = Security.class.getDeclaredField("secprops"); + field_secprops.setAccessible(true); + Properties secprops = (Properties) field_secprops.get(null); + secprops.remove(SSL_PROPERTY); + + Class<?> class_services = + Class.forName("org.apache.harmony.security.fortress.Services"); + Method m_setNeedRefresh = class_services.getMethod("setNeedRefresh"); + m_setNeedRefresh.invoke(null); + } catch (Exception e) { + e.printStackTrace(); + fail("Cannot find a way to clear out the SocketFactory provider"); + } + + assertNull(Security.getProperty(SSL_PROPERTY)); + return origProvider; + } + + public void test_SSLSocketFactory_defaultConfiguration() throws Exception { + SSLDefaultConfigurationAsserts.assertSSLSocketFactory( + (SSLSocketFactory) SSLSocketFactory.getDefault()); + } + + public void test_SSLSocketFactory_getDefaultCipherSuitesReturnsCopies() { SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault(); - String[] cipherSuites = sf.getDefaultCipherSuites(); - StandardNames.assertDefaultCipherSuites(cipherSuites); - assertNotSame(cipherSuites, sf.getDefaultCipherSuites()); + assertNotSame(sf.getDefaultCipherSuites(), sf.getDefaultCipherSuites()); } - public void test_SSLSocketFactory_getSupportedCipherSuites() { + public void test_SSLSocketFactory_getSupportedCipherSuitesReturnsCopies() { SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault(); - String[] cipherSuites = sf.getSupportedCipherSuites(); - StandardNames.assertValidCipherSuites(StandardNames.CIPHER_SUITES, cipherSuites); - assertNotSame(cipherSuites, sf.getSupportedCipherSuites()); + assertNotSame(sf.getSupportedCipherSuites(), sf.getSupportedCipherSuites()); } public void test_SSLSocketFactory_createSocket() throws Exception { diff --git a/luni/src/test/java/libcore/javax/net/ssl/SSLSocketTest.java b/luni/src/test/java/libcore/javax/net/ssl/SSLSocketTest.java index 8e009bd..4681877 100644 --- a/luni/src/test/java/libcore/javax/net/ssl/SSLSocketTest.java +++ b/luni/src/test/java/libcore/javax/net/ssl/SSLSocketTest.java @@ -16,6 +16,7 @@ package libcore.javax.net.ssl; +import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -33,12 +34,15 @@ import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import javax.net.ServerSocketFactory; import javax.net.ssl.HandshakeCompletedEvent; import javax.net.ssl.HandshakeCompletedListener; import javax.net.ssl.KeyManager; @@ -56,17 +60,22 @@ import javax.net.ssl.TrustManager; import javax.net.ssl.X509KeyManager; import javax.net.ssl.X509TrustManager; import junit.framework.TestCase; +import libcore.io.IoUtils; +import libcore.io.Streams; import libcore.java.security.StandardNames; import libcore.java.security.TestKeyStore; public class SSLSocketTest extends TestCase { - public void test_SSLSocket_getSupportedCipherSuites_names() throws Exception { + public void test_SSLSocket_defaultConfiguration() throws Exception { + SSLDefaultConfigurationAsserts.assertSSLSocket( + (SSLSocket) SSLSocketFactory.getDefault().createSocket()); + } + + public void test_SSLSocket_getSupportedCipherSuites_returnsCopies() throws Exception { SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket ssl = (SSLSocket) sf.createSocket(); - String[] cipherSuites = ssl.getSupportedCipherSuites(); - StandardNames.assertSupportedCipherSuites(StandardNames.CIPHER_SUITES, cipherSuites); - assertNotSame(cipherSuites, ssl.getSupportedCipherSuites()); + assertNotSame(ssl.getSupportedCipherSuites(), ssl.getSupportedCipherSuites()); } public void test_SSLSocket_getSupportedCipherSuites_connect() throws Exception { @@ -77,49 +86,13 @@ public class SSLSocketTest extends TestCase { .ca(true) .build(); StringBuilder error = new StringBuilder(); - if (StandardNames.IS_RI) { - test_SSLSocket_getSupportedCipherSuites_connect(testKeyStore, - StandardNames.JSSE_PROVIDER_NAME, - StandardNames.JSSE_PROVIDER_NAME, - true, - true, - error); - } else { - test_SSLSocket_getSupportedCipherSuites_connect(testKeyStore, - "HarmonyJSSE", - "HarmonyJSSE", - false, - false, - error); - test_SSLSocket_getSupportedCipherSuites_connect(testKeyStore, - "AndroidOpenSSL", - "AndroidOpenSSL", - true, - true, - error); - test_SSLSocket_getSupportedCipherSuites_connect(testKeyStore, - "HarmonyJSSE", - "AndroidOpenSSL", - false, - true, - error); - test_SSLSocket_getSupportedCipherSuites_connect(testKeyStore, - "AndroidOpenSSL", - "HarmonyJSSE", - true, - false, - error); - } + test_SSLSocket_getSupportedCipherSuites_connect(testKeyStore, error); if (error.length() > 0) { throw new Exception("One or more problems in " + "test_SSLSocket_getSupportedCipherSuites_connect:\n" + error); } } private void test_SSLSocket_getSupportedCipherSuites_connect(TestKeyStore testKeyStore, - String clientProvider, - String serverProvider, - boolean clientSecureRenegotiation, - boolean serverSecureRenegotiation, StringBuilder error) throws Exception { @@ -128,20 +101,18 @@ public class SSLSocketTest extends TestCase { byte[] clientToServer = clientToServerString.getBytes(); byte[] serverToClient = serverToClientString.getBytes(); - TestSSLContext c = TestSSLContext.create(testKeyStore, testKeyStore, - clientProvider, serverProvider); - String[] cipherSuites; - if (clientProvider.equals(serverProvider)) { - cipherSuites = c.clientContext.getSocketFactory().getSupportedCipherSuites(); - } else { - String[] clientSuites = c.clientContext.getSocketFactory().getSupportedCipherSuites(); - String[] serverSuites = c.serverContext.getSocketFactory().getSupportedCipherSuites(); - Set<String> ccs = new HashSet<String>(Arrays.asList(clientSuites)); - Set<String> scs = new HashSet<String>(Arrays.asList(serverSuites)); - Set<String> cs = new HashSet<String>(ccs); - cs.retainAll(scs); - cipherSuites = cs.toArray(new String[cs.size()]); - } + KeyManager pskKeyManager = PSKKeyManagerProxy.getConscryptPSKKeyManager( + new PSKKeyManagerProxy() { + @Override + protected SecretKey getKey(String identityHint, String identity, Socket socket) { + return new SecretKeySpec("Just an arbitrary key".getBytes(), "RAW"); + } + }); + TestSSLContext c = TestSSLContext.createWithAdditionalKeyManagers( + testKeyStore, testKeyStore, + new KeyManager[] {pskKeyManager}, new KeyManager[] {pskKeyManager}); + + String[] cipherSuites = c.clientContext.getSocketFactory().getSupportedCipherSuites(); for (String cipherSuite : cipherSuites) { boolean errorExpected = StandardNames.IS_RI && cipherSuite.endsWith("_SHA256"); @@ -171,41 +142,48 @@ public class SSLSocketTest extends TestCase { continue; } - String[] clientCipherSuiteArray - = (clientSecureRenegotiation - ? new String[] { cipherSuite, - StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION } - : new String[] { cipherSuite }); - String[] serverCipherSuiteArray - = (serverSecureRenegotiation - ? new String[] { cipherSuite, - StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION } - : new String[] { cipherSuite }); + String[] clientCipherSuiteArray = new String[] { + cipherSuite, + StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION }; + String[] serverCipherSuiteArray = clientCipherSuiteArray; SSLSocket[] pair = TestSSLSocketPair.connect(c, clientCipherSuiteArray, serverCipherSuiteArray); SSLSocket server = pair[0]; SSLSocket client = pair[1]; + + // Check that the client can read the message sent by the server server.getOutputStream().write(serverToClient); + byte[] clientFromServer = new byte[serverToClient.length]; + Streams.readFully(client.getInputStream(), clientFromServer); + assertEquals(serverToClientString, new String(clientFromServer)); + + // Check that the server can read the message sent by the client client.getOutputStream().write(clientToServer); - // arrays are too big to make sure we get back only what we expect - byte[] clientFromServer = new byte[serverToClient.length+1]; - byte[] serverFromClient = new byte[clientToServer.length+1]; - int readFromServer = client.getInputStream().read(clientFromServer); - int readFromClient = server.getInputStream().read(serverFromClient); - assertEquals(serverToClient.length, readFromServer); - assertEquals(clientToServer.length, readFromClient); - assertEquals(clientToServerString, new String(serverFromClient, 0, readFromClient)); - assertEquals(serverToClientString, new String(clientFromServer, 0, readFromServer)); + byte[] serverFromClient = new byte[clientToServer.length]; + Streams.readFully(server.getInputStream(), serverFromClient); + assertEquals(clientToServerString, new String(serverFromClient)); + + // Check that the server and the client cannot read anything else + // (reads should time out) + server.setSoTimeout(10); + try { + server.getInputStream().read(); + fail(); + } catch (IOException expected) {} + client.setSoTimeout(10); + try { + client.getInputStream().read(); + fail(); + } catch (IOException expected) {} + client.close(); server.close(); assertFalse(errorExpected); } catch (Exception maybeExpected) { if (!errorExpected) { - String message = ("Problem trying to connect cipher suite " + cipherSuite - + " client=" + clientProvider - + " server=" + serverProvider); + String message = ("Problem trying to connect cipher suite " + cipherSuite); System.out.println(message); maybeExpected.printStackTrace(); error.append(message); @@ -216,12 +194,20 @@ public class SSLSocketTest extends TestCase { c.close(); } - public void test_SSLSocket_getEnabledCipherSuites() throws Exception { + public void test_SSLSocket_getEnabledCipherSuites_returnsCopies() throws Exception { SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket ssl = (SSLSocket) sf.createSocket(); - String[] cipherSuites = ssl.getEnabledCipherSuites(); - StandardNames.assertValidCipherSuites(StandardNames.CIPHER_SUITES, cipherSuites); - assertNotSame(cipherSuites, ssl.getEnabledCipherSuites()); + assertNotSame(ssl.getEnabledCipherSuites(), ssl.getEnabledCipherSuites()); + } + + public void test_SSLSocket_setEnabledCipherSuites_storesCopy() throws Exception { + SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault(); + SSLSocket ssl = (SSLSocket) sf.createSocket(); + String[] array = new String[] {ssl.getEnabledCipherSuites()[0]}; + String originalFirstElement = array[0]; + ssl.setEnabledCipherSuites(array); + array[0] = "Modified after having been set"; + assertEquals(originalFirstElement, ssl.getEnabledCipherSuites()[0]); } public void test_SSLSocket_setEnabledCipherSuites() throws Exception { @@ -247,22 +233,33 @@ public class SSLSocketTest extends TestCase { ssl.setEnabledCipherSuites(new String[0]); ssl.setEnabledCipherSuites(ssl.getEnabledCipherSuites()); ssl.setEnabledCipherSuites(ssl.getSupportedCipherSuites()); + + // Check that setEnabledCipherSuites affects getEnabledCipherSuites + String[] cipherSuites = new String[] { ssl.getSupportedCipherSuites()[0] }; + ssl.setEnabledCipherSuites(cipherSuites); + assertEquals(Arrays.asList(cipherSuites), Arrays.asList(ssl.getEnabledCipherSuites())); } - public void test_SSLSocket_getSupportedProtocols() throws Exception { + public void test_SSLSocket_getSupportedProtocols_returnsCopies() throws Exception { SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket ssl = (SSLSocket) sf.createSocket(); - String[] protocols = ssl.getSupportedProtocols(); - StandardNames.assertSupportedProtocols(StandardNames.SSL_SOCKET_PROTOCOLS, protocols); - assertNotSame(protocols, ssl.getSupportedProtocols()); + assertNotSame(ssl.getSupportedProtocols(), ssl.getSupportedProtocols()); } - public void test_SSLSocket_getEnabledProtocols() throws Exception { + public void test_SSLSocket_getEnabledProtocols_returnsCopies() throws Exception { SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket ssl = (SSLSocket) sf.createSocket(); - String[] protocols = ssl.getEnabledProtocols(); - StandardNames.assertValidProtocols(StandardNames.SSL_SOCKET_PROTOCOLS, protocols); - assertNotSame(protocols, ssl.getEnabledProtocols()); + assertNotSame(ssl.getEnabledProtocols(), ssl.getEnabledProtocols()); + } + + public void test_SSLSocket_setEnabledProtocols_storesCopy() throws Exception { + SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault(); + SSLSocket ssl = (SSLSocket) sf.createSocket(); + String[] array = new String[] {ssl.getEnabledProtocols()[0]}; + String originalFirstElement = array[0]; + ssl.setEnabledProtocols(array); + array[0] = "Modified after having been set"; + assertEquals(originalFirstElement, ssl.getEnabledProtocols()[0]); } public void test_SSLSocket_setEnabledProtocols() throws Exception { @@ -287,6 +284,21 @@ public class SSLSocketTest extends TestCase { ssl.setEnabledProtocols(new String[0]); ssl.setEnabledProtocols(ssl.getEnabledProtocols()); ssl.setEnabledProtocols(ssl.getSupportedProtocols()); + + // Check that setEnabledProtocols affects getEnabledProtocols + for (String protocol : ssl.getSupportedProtocols()) { + if ("SSLv2Hello".equals(protocol)) { + try { + ssl.setEnabledProtocols(new String[] { protocol }); + fail("Should fail when SSLv2Hello is set by itself"); + } catch (IllegalArgumentException expected) {} + } else { + String[] protocols = new String[] { protocol }; + ssl.setEnabledProtocols(protocols); + assertEquals(Arrays.deepToString(protocols), + Arrays.deepToString(ssl.getEnabledProtocols())); + } + } } public void test_SSLSocket_getSession() throws Exception { @@ -394,35 +406,26 @@ public class SSLSocketTest extends TestCase { SSLContext.getDefault(), SSLContext.getDefault()); SSLSocket client = (SSLSocket) c.clientContext.getSocketFactory().createSocket(c.host, c.port); - // RI used to throw SSLException on accept, now throws on startHandshake - if (StandardNames.IS_RI) { - final SSLSocket server = (SSLSocket) c.serverSocket.accept(); - ExecutorService executor = Executors.newSingleThreadExecutor(); - Future<Void> future = executor.submit(new Callable<Void>() { - @Override public Void call() throws Exception { - try { - server.startHandshake(); - fail(); - } catch (SSLHandshakeException expected) { - } - return null; + final SSLSocket server = (SSLSocket) c.serverSocket.accept(); + ExecutorService executor = Executors.newSingleThreadExecutor(); + Future<Void> future = executor.submit(new Callable<Void>() { + @Override public Void call() throws Exception { + try { + server.startHandshake(); + fail(); + } catch (SSLHandshakeException expected) { } - }); - executor.shutdown(); - try { - client.startHandshake(); - fail(); - } catch (SSLHandshakeException expected) { - } - future.get(); - server.close(); - } else { - try { - c.serverSocket.accept(); - fail(); - } catch (SSLException expected) { + return null; } + }); + executor.shutdown(); + try { + client.startHandshake(); + fail(); + } catch (SSLHandshakeException expected) { } + future.get(); + server.close(); client.close(); c.close(); } @@ -526,6 +529,8 @@ public class SSLSocketTest extends TestCase { assertNotNull(socket); assertSame(client, socket); + assertTrue(socket instanceof SSLSocket); + synchronized (handshakeCompletedListenerCalled) { handshakeCompletedListenerCalled[0] = true; handshakeCompletedListenerCalled.notify(); @@ -675,7 +680,7 @@ public class SSLSocketTest extends TestCase { public void test_SSLSocket_setUseClientMode_afterHandshake() throws Exception { // can't set after handshake - TestSSLEnginePair pair = TestSSLEnginePair.create(null); + TestSSLSocketPair pair = TestSSLSocketPair.create(); try { pair.server.setUseClientMode(false); fail(); @@ -699,9 +704,8 @@ public class SSLSocketTest extends TestCase { @Override public Void call() throws Exception { try { server.startHandshake(); - assertFalse(StandardNames.IS_RI); + fail(); } catch (SSLHandshakeException expected) { - assertTrue(StandardNames.IS_RI); } return null; } @@ -713,9 +717,10 @@ public class SSLSocketTest extends TestCase { } catch (SSLHandshakeException expected) { assertTrue(expected.getCause() instanceof CertificateException); } + future.get(); client.close(); server.close(); - future.get(); + c.close(); } public void test_SSLSocket_clientAuth() throws Exception { @@ -846,7 +851,11 @@ public class SSLSocketTest extends TestCase { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<Void> future = executor.submit(new Callable<Void>() { @Override public Void call() throws Exception { - server.startHandshake(); + try { + server.startHandshake(); + fail(); + } catch (SSLHandshakeException expected) { + } return null; } }); @@ -942,12 +951,10 @@ public class SSLSocketTest extends TestCase { assertNotNull(p); String[] cipherSuites = p.getCipherSuites(); - StandardNames.assertValidCipherSuites(StandardNames.CIPHER_SUITES, cipherSuites); assertNotSame(cipherSuites, ssl.getEnabledCipherSuites()); assertEquals(Arrays.asList(cipherSuites), Arrays.asList(ssl.getEnabledCipherSuites())); String[] protocols = p.getProtocols(); - StandardNames.assertValidProtocols(StandardNames.SSL_SOCKET_PROTOCOLS, protocols); assertNotSame(protocols, ssl.getEnabledProtocols()); assertEquals(Arrays.asList(protocols), Arrays.asList(ssl.getEnabledProtocols())); @@ -1327,10 +1334,7 @@ public class SSLSocketTest extends TestCase { test_SSLSocket_interrupt_case(true, true); test_SSLSocket_interrupt_case(true, false); test_SSLSocket_interrupt_case(false, true); - // Currently failing due to reader blocking closing thread http://b/10681815 - if (StandardNames.IS_RI) { - test_SSLSocket_interrupt_case(false, false); - } + test_SSLSocket_interrupt_case(false, false); } private void test_SSLSocket_interrupt_case(boolean readUnderlying, boolean closeUnderlying) @@ -1373,7 +1377,7 @@ public class SSLSocketTest extends TestCase { /** * b/7014266 Test to confirm that an SSLSocket.close() on one - * thread will interupt another thread blocked reading on the same + * thread will interrupt another thread blocked reading on the same * socket. */ public void test_SSLSocket_interrupt_read() throws Exception { @@ -1384,7 +1388,16 @@ public class SSLSocketTest extends TestCase { c.host.getHostName(), c.port, false); - ExecutorService executor = Executors.newSingleThreadExecutor(); + + // Create our own thread group so we can inspect the stack state later. + final ThreadGroup clientGroup = new ThreadGroup("client"); + ExecutorService executor = Executors.newSingleThreadExecutor(new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + return new Thread(clientGroup, r); + } + }); + Future<Void> clientFuture = executor.submit(new Callable<Void>() { @Override public Void call() throws Exception { try { @@ -1402,6 +1415,26 @@ public class SSLSocketTest extends TestCase { SSLSocket server = (SSLSocket) c.serverSocket.accept(); server.startHandshake(); + + /* + * Wait for the client to at least be in the "read" method before + * calling close() + */ + Thread[] threads = new Thread[1]; + clientGroup.enumerate(threads); + if (threads[0] != null) { + boolean clientInRead = false; + while (!clientInRead) { + StackTraceElement[] elements = threads[0].getStackTrace(); + for (StackTraceElement element : elements) { + if ("read".equals(element.getMethodName())) { + clientInRead = true; + break; + } + } + } + } + wrapping.close(); clientFuture.get(); server.close(); @@ -1423,6 +1456,120 @@ public class SSLSocketTest extends TestCase { test.close(); } + public void test_SSLSocket_ClientHello_size() throws Exception { + // This test checks the size of ClientHello of the default SSLSocket. TLS/SSL handshakes + // with older/unpatched F5/BIG-IP appliances are known to stall and time out when + // the fragment containing ClientHello is between 256 and 511 (inclusive) bytes long. + // + // Since there's no straightforward way to obtain a ClientHello from SSLSocket, this test + // does the following: + // 1. Creates a listening server socket (a plain one rather than a TLS/SSL one). + // 2. Creates a client SSLSocket, which connects to the server socket and initiates the + // TLS/SSL handshake. + // 3. Makes the server socket accept an incoming connection on the server socket, and reads + // the first chunk of data received. This chunk is assumed to be the ClientHello. + // NOTE: Steps 2 and 3 run concurrently. + ServerSocket listeningSocket = null; + ExecutorService executorService = Executors.newFixedThreadPool(2); + + // Some Socket operations are not interruptible via Thread.interrupt for some reason. To + // work around, we unblock these sockets using Socket.close. + final Socket[] sockets = new Socket[2]; + try { + // 1. Create the listening server socket. + listeningSocket = ServerSocketFactory.getDefault().createServerSocket(0); + final ServerSocket finalListeningSocket = listeningSocket; + // 2. (in background) Wait for an incoming connection and read its first chunk. + final Future<byte[]> readFirstReceivedChunkFuture = + executorService.submit(new Callable<byte[]>() { + @Override + public byte[] call() throws Exception { + Socket socket = finalListeningSocket.accept(); + sockets[1] = socket; + try { + byte[] buffer = new byte[64 * 1024]; + int bytesRead = socket.getInputStream().read(buffer); + if (bytesRead == -1) { + throw new EOFException("Failed to read anything"); + } + return Arrays.copyOf(buffer, bytesRead); + } finally { + IoUtils.closeQuietly(socket); + } + } + }); + + // 3. Create a client socket, connect it to the server socket, and start the TLS/SSL + // handshake. + executorService.submit(new Callable<Void>() { + @Override + public Void call() throws Exception { + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, null, null); + SSLSocket client = (SSLSocket) sslContext.getSocketFactory().createSocket(); + sockets[0] = client; + try { + // Enable SNI extension on the socket (this is typically enabled by default) + // to increase the size of ClientHello. + try { + Method setHostname = + client.getClass().getMethod("setHostname", String.class); + setHostname.invoke(client, "sslsockettest.androidcts.google.com"); + } catch (NoSuchMethodException ignored) {} + + // Enable Session Tickets extension on the socket (this is typically enabled + // by default) to increase the size of ClientHello. + try { + Method setUseSessionTickets = + client.getClass().getMethod( + "setUseSessionTickets", boolean.class); + setUseSessionTickets.invoke(client, true); + } catch (NoSuchMethodException ignored) {} + + client.connect(finalListeningSocket.getLocalSocketAddress()); + // Initiate the TLS/SSL handshake which is expected to fail as soon as the + // server socket receives a ClientHello. + try { + client.startHandshake(); + fail(); + return null; + } catch (IOException expected) {} + return null; + } finally { + IoUtils.closeQuietly(client); + + // Cancel the reading task. If this task succeeded, then the reading task + // is done and this will have no effect. If this task failed prematurely, + // then the reading task might get unblocked (we're interrupting the thread + // it's running on), will fail early, and we'll thus save some time in this + // test. + readFirstReceivedChunkFuture.cancel(true); + } + } + }); + + // Wait for the ClientHello to arrive + byte[] clientHello = readFirstReceivedChunkFuture.get(10, TimeUnit.SECONDS); + + // Check for ClientHello length that may cause handshake to fail/time out with older + // F5/BIG-IP appliances. + assertEquals("TLS record type: handshake", 22, clientHello[0]); + int fragmentLength = ((clientHello[3] & 0xff) << 8) | (clientHello[4] & 0xff); + if ((fragmentLength >= 256) && (fragmentLength <= 511)) { + fail("Fragment containing ClientHello is of dangerous length: " + + fragmentLength + " bytes"); + } + } finally { + executorService.shutdownNow(); + IoUtils.closeQuietly(listeningSocket); + IoUtils.closeQuietly(sockets[0]); + IoUtils.closeQuietly(sockets[1]); + if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) { + fail("Timed out while waiting for the test to shut down"); + } + } + } + public void test_SSLSocket_sendsTlsFallbackScsv_Fallback_Success() throws Exception { TestSSLContext context = TestSSLContext.create(); @@ -1461,6 +1608,42 @@ public class SSLSocketTest extends TestCase { context.close(); } + // Confirms that communication without the TLS_FALLBACK_SCSV cipher works as it always did. + public void test_SSLSocket_sendsNoTlsFallbackScsv_Fallback_Success() throws Exception { + TestSSLContext context = TestSSLContext.create(); + + final SSLSocket client = (SSLSocket) + context.clientContext.getSocketFactory().createSocket(context.host, context.port); + final SSLSocket server = (SSLSocket) context.serverSocket.accept(); + + // Confirm absence of TLS_FALLBACK_SCSV. + assertFalse(Arrays.asList(client.getEnabledCipherSuites()) + .contains(StandardNames.CIPHER_SUITE_FALLBACK)); + + ExecutorService executor = Executors.newFixedThreadPool(2); + Future<Void> s = executor.submit(new Callable<Void>() { + public Void call() throws Exception { + server.setEnabledProtocols(new String[] { "TLSv1", "SSLv3" }); + server.startHandshake(); + return null; + } + }); + Future<Void> c = executor.submit(new Callable<Void>() { + public Void call() throws Exception { + client.setEnabledProtocols(new String[] { "SSLv3" }); + client.startHandshake(); + return null; + } + }); + executor.shutdown(); + + s.get(); + c.get(); + client.close(); + server.close(); + context.close(); + } + public void test_SSLSocket_sendsTlsFallbackScsv_InappropriateFallback_Failure() throws Exception { TestSSLContext context = TestSSLContext.create(); @@ -1469,6 +1652,8 @@ public class SSLSocketTest extends TestCase { final SSLSocket server = (SSLSocket) context.serverSocket.accept(); final String[] serverCipherSuites = server.getEnabledCipherSuites(); + + // Add TLS_FALLBACK_SCSV final String[] clientCipherSuites = new String[serverCipherSuites.length + 1]; System.arraycopy(serverCipherSuites, 0, clientCipherSuites, 0, serverCipherSuites.length); clientCipherSuites[serverCipherSuites.length] = StandardNames.CIPHER_SUITE_FALLBACK; diff --git a/luni/src/test/java/libcore/javax/security/auth/x500/X500PrincipalTest.java b/luni/src/test/java/libcore/javax/security/auth/x500/X500PrincipalTest.java index 7ee5778..571aa9c 100644 --- a/luni/src/test/java/libcore/javax/security/auth/x500/X500PrincipalTest.java +++ b/luni/src/test/java/libcore/javax/security/auth/x500/X500PrincipalTest.java @@ -57,20 +57,21 @@ public class X500PrincipalTest extends TestCase { */ public void testGetName() throws Exception { CertificateFactory certFactBC = CertificateFactory.getInstance("X.509", "BC"); - CertificateFactory certFactDRL = CertificateFactory.getInstance("X.509", "DRLCertFactory"); + CertificateFactory certFactOpenSSL = CertificateFactory.getInstance("X.509", + "AndroidOpenSSL"); X509Certificate certBC = (X509Certificate) certFactBC.generateCertificate(new ByteArrayInputStream(T61STRING_CERT)); - X509Certificate certDRL = (X509Certificate) - certFactDRL.generateCertificate(new ByteArrayInputStream(T61STRING_CERT)); + X509Certificate certOpenSSL = (X509Certificate) + certFactOpenSSL.generateCertificate(new ByteArrayInputStream(T61STRING_CERT)); - assertEquals(certBC, certDRL); + assertEquals(certBC, certOpenSSL); assertEquals(certBC.getSubjectX500Principal(), certBC.getSubjectX500Principal()); - assertEquals(certDRL.getIssuerX500Principal(), certDRL.getIssuerX500Principal()); + assertEquals(certOpenSSL.getIssuerX500Principal(), certOpenSSL.getIssuerX500Principal()); - assertEquals(certBC.getSubjectX500Principal(), certDRL.getSubjectX500Principal()); - assertEquals(certBC.getIssuerX500Principal(), certDRL.getIssuerX500Principal()); + assertEquals(certBC.getSubjectX500Principal(), certOpenSSL.getSubjectX500Principal()); + assertEquals(certBC.getIssuerX500Principal(), certOpenSSL.getIssuerX500Principal()); String[] formats = { X500Principal.CANONICAL, @@ -79,9 +80,9 @@ public class X500PrincipalTest extends TestCase { }; for (String format : formats) { assertEquals(certBC.getSubjectX500Principal().getName(format), - certDRL.getSubjectX500Principal().getName(format)); + certOpenSSL.getSubjectX500Principal().getName(format)); assertEquals(certBC.getIssuerX500Principal().getName(format), - certDRL.getIssuerX500Principal().getName(format)); + certOpenSSL.getIssuerX500Principal().getName(format)); } String expected = "" + "cn=entrust.net certification authority (2048)," diff --git a/luni/src/test/java/libcore/net/MimeUtilsTest.java b/luni/src/test/java/libcore/net/MimeUtilsTest.java new file mode 100644 index 0000000..36476e9 --- /dev/null +++ b/luni/src/test/java/libcore/net/MimeUtilsTest.java @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2014 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.net; + +import junit.framework.TestCase; + +import libcore.net.MimeUtils; + +public class MimeUtilsTest extends TestCase { + public void test_15715370() { + assertEquals("audio/flac", MimeUtils.guessMimeTypeFromExtension("flac")); + assertEquals("flac", MimeUtils.guessExtensionFromMimeType("audio/flac")); + assertEquals("flac", MimeUtils.guessExtensionFromMimeType("application/x-flac")); + } + + public void test_16978217() { + assertEquals("image/x-ms-bmp", MimeUtils.guessMimeTypeFromExtension("bmp")); + assertEquals("image/x-icon", MimeUtils.guessMimeTypeFromExtension("ico")); + assertEquals("video/mp2ts", MimeUtils.guessMimeTypeFromExtension("ts")); + } + + public void testCommon() { + assertEquals("audio/mpeg", MimeUtils.guessMimeTypeFromExtension("mp3")); + assertEquals("image/png", MimeUtils.guessMimeTypeFromExtension("png")); + assertEquals("application/zip", MimeUtils.guessMimeTypeFromExtension("zip")); + + assertEquals("mp3", MimeUtils.guessExtensionFromMimeType("audio/mpeg")); + assertEquals("png", MimeUtils.guessExtensionFromMimeType("image/png")); + assertEquals("zip", MimeUtils.guessExtensionFromMimeType("application/zip")); + } +} diff --git a/luni/src/test/java/libcore/net/event/NetworkEventDispatcherTest.java b/luni/src/test/java/libcore/net/event/NetworkEventDispatcherTest.java new file mode 100644 index 0000000..dc32da6 --- /dev/null +++ b/luni/src/test/java/libcore/net/event/NetworkEventDispatcherTest.java @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2014 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.net.event; + +import junit.framework.TestCase; + +/** + * Tests for {@link NetworkEventDispatcher}. + */ +public class NetworkEventDispatcherTest extends TestCase { + + public void testGetInstance_isSingleton() { + assertSame(NetworkEventDispatcher.getInstance(), NetworkEventDispatcher.getInstance()); + } + + public void testAddListener_null() throws Exception { + NetworkEventDispatcher networkEventDispatcher = new NetworkEventDispatcher() {}; + try { + networkEventDispatcher.addListener(null); + fail(); + } catch (NullPointerException expected) { + } + } + + public void testOnNetworkConfigurationChanged_noListeners() throws Exception { + NetworkEventDispatcher networkEventDispatcher = new NetworkEventDispatcher() {}; + networkEventDispatcher.onNetworkConfigurationChanged(); + } + + public void testFireNetworkEvent_oneListener() throws Exception { + FakeNetworkEventListener listener = new FakeNetworkEventListener(); + NetworkEventDispatcher networkEventDispatcher = new NetworkEventDispatcher() {}; + networkEventDispatcher.addListener(listener); + + networkEventDispatcher.onNetworkConfigurationChanged(); + + listener.assertNetworkConfigurationChangedEvent(1); + } + + public void testRemoveEventListener() throws Exception { + FakeNetworkEventListener listener = new FakeNetworkEventListener(); + NetworkEventDispatcher networkEventDispatcher = new NetworkEventDispatcher() {}; + networkEventDispatcher.addListener(listener); + networkEventDispatcher.removeListener(listener); + + networkEventDispatcher.onNetworkConfigurationChanged(); + + listener.assertNetworkConfigurationChangedEvent(0); + } + + private static class FakeNetworkEventListener extends NetworkEventListener { + + private int networkConfigurationChangedCount; + + @Override + public void onNetworkConfigurationChanged() { + networkConfigurationChangedCount++; + } + + public void assertNetworkConfigurationChangedEvent(int expectedCount) { + assertEquals(expectedCount, networkConfigurationChangedCount); + } + } +} diff --git a/luni/src/test/java/libcore/reflect/InternalNamesTest.java b/luni/src/test/java/libcore/reflect/InternalNamesTest.java new file mode 100644 index 0000000..bb305ff --- /dev/null +++ b/luni/src/test/java/libcore/reflect/InternalNamesTest.java @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2011 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.reflect; + +import junit.framework.TestCase; + +public final class InternalNamesTest extends TestCase { + private final ClassLoader loader = InternalNames.class.getClassLoader(); + + public void testGetClassNull() { + try { + InternalNames.getClass(loader, null); + fail(); + } catch (NullPointerException expected) { + } + } + + public void testGetInternalNameNull() { + try { + InternalNames.getInternalName(null); + fail(); + } catch (NullPointerException expected) { + } + } + + public void testInternalNameToPrimitive() { + assertEquals(byte.class, InternalNames.getClass(loader, "B")); + assertEquals(char.class, InternalNames.getClass(loader, "C")); + assertEquals(double.class, InternalNames.getClass(loader, "D")); + assertEquals(float.class, InternalNames.getClass(loader, "F")); + assertEquals(int.class, InternalNames.getClass(loader, "I")); + assertEquals(long.class, InternalNames.getClass(loader, "J")); + assertEquals(short.class, InternalNames.getClass(loader, "S")); + assertEquals(boolean.class, InternalNames.getClass(loader, "Z")); + assertEquals(void.class, InternalNames.getClass(loader, "V")); + } + + public void testPrimitiveToInternalName() { + assertEquals("B", InternalNames.getInternalName(byte.class)); + assertEquals("C", InternalNames.getInternalName(char.class)); + assertEquals("D", InternalNames.getInternalName(double.class)); + assertEquals("F", InternalNames.getInternalName(float.class)); + assertEquals("I", InternalNames.getInternalName(int.class)); + assertEquals("J", InternalNames.getInternalName(long.class)); + assertEquals("S", InternalNames.getInternalName(short.class)); + assertEquals("Z", InternalNames.getInternalName(boolean.class)); + assertEquals("V", InternalNames.getInternalName(void.class)); + } + + public void testInternalNameToClass() { + assertEquals(String.class, InternalNames.getClass(loader, "Ljava/lang/String;")); + } + + public void testClassToInternalName() { + assertEquals("Ljava/lang/String;", InternalNames.getInternalName(String.class)); + } + + public void testInternalNameToPrimitiveArray() { + assertEquals(int[].class, InternalNames.getClass(loader, "[I")); + assertEquals(int[][][][].class, InternalNames.getClass(loader, "[[[[I")); + } + + public void testInternalNameToObjectArray() { + assertEquals(String[].class, InternalNames.getClass(loader, "[Ljava/lang/String;")); + assertEquals(String[][][][].class, + InternalNames.getClass(loader, "[[[[Ljava/lang/String;")); + } +} diff --git a/luni/src/test/java/libcore/sqlite/AbstractSqlTest.java b/luni/src/test/java/libcore/sqlite/AbstractSqlTest.java deleted file mode 100644 index d194548..0000000 --- a/luni/src/test/java/libcore/sqlite/AbstractSqlTest.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright (C) 2007 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.sqlite; - -import SQLite.Exception; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import junit.framework.TestCase; - - -/** - * This class provides SQL unit test, which can be used by subclasses eg. to - * test JDBC drivers. - */ -abstract class AbstractSqlTest extends TestCase { - - /** - * The first connection. - */ - private Connection firstConnection; - - /** - * The second connection. - */ - private Connection secondConnection; - - /** - * The statement from the first connection. - */ - private Statement firstStmt; - - /** - * The statement from the second connection. - */ - private Statement secondStmt; - - /** - * The values of the first column "one". - */ - private final String[] ones = {"hello!", "goodbye"}; - - /** - * The values of the second column "two". - */ - private final short[] twos = {10, 20}; - - /** - * The updated values of the first column "one". - */ - private final String[] ones_updated; - - /** Creates a new instance of this class */ - public AbstractSqlTest() { - super(); - ones_updated = new String[ones.length]; - for (int i = 0; i < ones.length; i++) { - ones_updated[i] = ones[i] + twos[i]; - } - } - - /** - * Sets up a unit test, by creating two statements from two connections and - * creating a test table. - * - * @exception SQLException if there is a problem accessing the database - * @throws Exception - * @exception Exception may be thrown by subclasses - */ - @Override - protected void setUp() throws java.lang.Exception { - Class.forName(getDriverClassName()).newInstance(); - firstConnection = DriverManager.getConnection(getConnectionURL()); - firstConnection.setTransactionIsolation(getTransactionIsolation()); - secondConnection = DriverManager.getConnection(getConnectionURL()); - secondConnection.setTransactionIsolation(getTransactionIsolation()); - firstStmt = firstConnection.createStatement(); - firstStmt.execute("create table tbl1(one varchar(10), two smallint)"); - secondStmt = secondConnection.createStatement(); - } - - /** - * Tears down a unit test, by setting the auto commit property of the first - * connection back to true, dropping the test table and closing the two - * connections. - */ - @Override - protected void tearDown() throws SQLException { - firstStmt.close(); - secondStmt.close(); - firstConnection.setAutoCommit(true); - firstStmt = firstConnection.createStatement(); - firstStmt.execute("drop table tbl1"); - firstStmt.close(); - firstConnection.close(); - secondConnection.close(); - } - - /** - * Adds some rows to the test table and asserts that the rows can be - * retrieved again. - * - * @throws SQLException if there is a problem accessing the database - */ - private void autoCommitInsertSelect() throws SQLException { - firstStmt.getConnection().setAutoCommit(true); - for (int i = 0; i < ones.length; i++) { - firstStmt.execute("insert into tbl1 values('" + ones[i] + "'," - + twos[i] + ")"); - } - assertAllFromTbl1(firstStmt, ones, twos); - } - - /** - * Asserts that the expected values can be selected from the test table. - * - * @param stmt the statement to be used for the selection of the data - * @param ones the expected values of the column 'one' - * @param twos the expected values of the column 'two' - * @throws SQLException if there is a problem accessing the database - */ - private void assertAllFromTbl1(Statement stmt, String[] ones, short[] twos) - throws SQLException { - ResultSet rs = stmt.executeQuery("select * from tbl1"); - int i = 0; - for (; rs.next(); i++) { - assertTrue(i < ones.length); - assertEquals(ones[i], rs.getString("one")); - assertEquals(twos[i], rs.getShort("two")); - } - assertTrue(i == ones.length); - } - - public void testAutoCommitInsertSelect() throws SQLException{ - autoCommitInsertSelect(); - } - - /** - * Tests the following sequence after successful insertion of some test - * data: - * - update data from connection one - * - select data from connection two (-> should have the old values) - * - commit data from connection one - * - select data from connection two (-> should have the new values) - * - * @throws SQLException if there is a problem accessing the database - */ - public void testUpdateSelectCommitSelect() throws SQLException { - autoCommitInsertSelect(); - firstStmt.getConnection().setAutoCommit(false); - updateOnes(firstStmt, ones_updated, twos); - assertAllFromTbl1(secondStmt, ones, twos); - firstStmt.getConnection().commit(); - assertAllFromTbl1(secondStmt, ones_updated, twos); - } - - /** - * Tests the following sequence after successful insertion of some test - * data: - * - update data from connection one - * - select data from connection two (-> should have the old values) - * - rollback data from connection one - * - select data from connection two (-> should still have the old values) - * - * @throws SQLException if there is a problem accessing the database - */ - public void testUpdateSelectRollbackSelect() throws SQLException { - autoCommitInsertSelect(); - firstStmt.getConnection().setAutoCommit(false); - updateOnes(firstStmt, ones_updated, twos); - assertAllFromTbl1(secondStmt, ones, twos); - firstStmt.getConnection().rollback(); - assertAllFromTbl1(secondStmt, ones, twos); - } - - /** - * Updates the values in column 'one' - * @param stmt the statement to be used to update the data - * @param ones_updated the updated valus of column 'one' - * @param twos the reference values of column 'two' - * @throws SQLException if there is a problem accessing the database - */ - private void updateOnes(Statement stmt, String[] ones_updated, short[] twos) - throws SQLException { - for (int i = 0; i < ones_updated.length; i++) { - stmt.execute("UPDATE tbl1 SET one = '" + ones_updated[i] - + "' WHERE two = " + twos[i]); - } - } - - protected abstract String getConnectionURL(); - - protected abstract String getDriverClassName(); - - protected abstract int getTransactionIsolation(); - -} diff --git a/luni/src/test/java/libcore/sqlite/OldBlobTest.java b/luni/src/test/java/libcore/sqlite/OldBlobTest.java deleted file mode 100644 index 3289d38..0000000 --- a/luni/src/test/java/libcore/sqlite/OldBlobTest.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (C) 2008 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.sqlite; - -import SQLite.Blob; -import SQLite.Database; -import SQLite.Exception; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import tests.support.Support_SQL; - -public final class OldBlobTest extends OldSQLiteTest { - - private static Blob testBlob = null; - - private static Database db = null; - - public void setUp() throws java.lang.Exception { - super.setUp(); - testBlob = new Blob(); - - super.setUp(); - Support_SQL.loadDriver(); - db = new Database(); - db.open(dbFile.getPath(), 0); - - db.exec("create table B(id integer primary key, val blob)",null); - db.exec("insert into B values(1, zeroblob(128))", null); - db.exec("insert into B values(2, zeroblob(128))", null); - db.exec("insert into B values(3, zeroblob(128))", null); - - // can not fill Blob with data at this point... - /* - File resources = Support_Resources.createTempFolder(); - BufferedReader r = null; - try { - Class c = Class.forName(this.getClass().getName()); - assertNotNull(c); - file = Class.forName(this.getClass().getName()) - .getResourceAsStream("/blob.c"); - r = new BufferedReader(new InputStreamReader(file)); - } catch (NullPointerException e) { - fail("Should not throw NullPointerException reading file" - + e.getMessage()); - } - OutputStream out = testBlob.getOutputStream(); - String s = null; - while ((s = r.readLine()) != null) { - out.write(r.readLine().getBytes()); - } - out.flush(); - out.close(); - testBlob.close(); - */ - } - - @Override public void tearDown() throws java.lang.Exception { - testBlob.close(); - super.tearDown(); - } - - /** - * db.open_blob is not supported. - */ - public void testBlob() throws Exception, IOException { - byte[] b = new byte[4]; - byte[] b128 = new byte[128]; - for (int i = 0; i < b128.length; i++) { - b128[i] = (byte) i; - } - Blob blob = db.open_blob(dbFile.getPath(), "B", "val", 1, true); - try { - - OutputStream os = blob.getOutputStream(); - os.write(b128); - os.close(); - - InputStream is = blob.getInputStream(); - is.skip(96); - assertEquals(4,is.read(b)); - is.close(); - } finally { - blob.close(); - } - } - - public void testGetInputStream() { - InputStream in = testBlob.getInputStream(); - try { - in.read(); - fail("Exception not thrown for invalid Blob."); - } catch (Throwable e) { - //ok - } - } - - public void testGetOutputStream() { - OutputStream out = testBlob.getOutputStream(); - - try { - out.write(null); - fail("Write operation unsupported"); - } catch (Throwable e) { - assertEquals("Write operation unsupported", e.getMessage()); - } - } - - public void testClose() { - assertNotNull(testBlob); - - testBlob.close(); - // inputStream either null or some error occurs - try { - // TODO This does look a bit weird. Revisit later. - assertNull(testBlob.getInputStream()); - } catch (Throwable e) { - //ok - } - } -} diff --git a/luni/src/test/java/libcore/sqlite/OldDatabaseTest.java b/luni/src/test/java/libcore/sqlite/OldDatabaseTest.java deleted file mode 100644 index f2cbc57..0000000 --- a/luni/src/test/java/libcore/sqlite/OldDatabaseTest.java +++ /dev/null @@ -1,1224 +0,0 @@ -/* - * Copyright (C) 2008 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.sqlite; - -import SQLite.Authorizer; -import SQLite.Blob; -import SQLite.BusyHandler; -import SQLite.Callback; -import SQLite.Constants; -import SQLite.Database; -import SQLite.Exception; -import SQLite.Function; -import SQLite.FunctionContext; -import SQLite.ProgressHandler; -import SQLite.Stmt; -import SQLite.TableResult; -import SQLite.Trace; -import SQLite.Vm; -import java.io.File; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.net.URL; -import java.sql.DatabaseMetaData; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.logging.Logger; -import tests.support.DatabaseCreator; -import tests.support.MockFunction; -import tests.support.ThreadPool; - -public final class OldDatabaseTest extends OldSQLiteTest { - - private static ErrorTracker tracker = null; - - private Statement statement; - - private Database db = null; - - private static final int numThreads = 10; - - private static final int numOfRecords = 30; - - @Override public void setUp() throws java.lang.Exception { - super.setUp(); - assertNotNull("Could not establish DB connection",conn); - tracker = new ErrorTracker(); - - statement = conn.createStatement(); - - // Cleanup tables if necessary - - DatabaseMetaData meta = conn.getMetaData(); - assertNotNull(meta); - ResultSet userTab = meta.getTables(null, null, null, null); - while (userTab.next()) { - String tableName = userTab.getString("TABLE_NAME"); - this.statement.execute("drop table " + tableName); - } - - // Create default test table - statement.execute(DatabaseCreator.CREATE_TABLE_SIMPLE1); - statement.close(); - - db = new Database(); - db.open(dbFile.getPath(), 0); - db.busy_handler(null); - } - - public void tearDown() throws java.lang.Exception { - try { - db.close(); - } catch (Exception e) { - if (!(e.getMessage().equals("database already closed"))) { - System.err.println("Error closing DB " + dbFile.getPath()); - } - } - tracker.reset(); - super.tearDown(); - } - - public void testDatabase() throws Exception { - // db closed - Database db2 = new Database(); - db.close(); - db2 = new Database(); - db2.open(dbFile.getPath(), 0); - db2.close(); - db.open(dbFile.getPath(), 0); - //db is open - db2.open(dbFile.getPath(), 0); - db2.close(); - } - - public void testOpen() throws Exception { - db.close(); - db.open(dbFile.getPath(), 0); - // open second db while db1 still open - Database db2 = new Database(); - db2.open(dbFile.getPath(), 0); - db2.open(dbFile.getPath(), 0); - db2.close(); - // open non db file - try { - URL file = OldDatabaseTest.class.getResource("/blob.c"); - db2.open(file.getPath(), 0); - fail("Should not be able to open non db file"); - } catch (SQLite.Exception e) { - assertEquals("unknown error in open", e.getMessage()); - } - } - - public void testOpen_aux_file() { - File temp = null; - try { - db.open_aux_file(""); - fail("open should fail"); - } catch (Exception e) { - assertEquals("unsupported", e.getMessage()); - } - - /* - try { - temp = File.createTempFile("openAuxMethod", ".db"); - db.open_aux_file(""); - db.exec("create table AUX_TABLE", null); - db.close(); - } catch (Exception e) { - temp.delete(); - fail("Error handling temporary file "+e.getMessage()); - e.printStackTrace(); - } catch (IOException e) { - temp.delete(); - fail("Could not create temporary File"); - e.printStackTrace(); - } - try { - db.open(dbFile.getPath(),0); - db.exec("select * from AUX_TABLE", null); - fail("Statement should fail"); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - temp.delete(); - */ - } - - public void testClose() throws Exception { - try { - db.close(); - db.get_table("test"); - fail(); - } catch (Exception e) { - assertTrue(e.getMessage().equals("database already closed")); - try { - db.open(dbFile.getPath(), 0); - } catch (Exception e1) { - fail("Database object could not be reopened after 'close': " - + e.getMessage()); - e1.printStackTrace(); - } - } - - try { - db.close(); - db.close(); - fail(); - } catch (Exception e) { - assertTrue(e.getMessage().equals("database already closed")); - db.open(dbFile.getPath(), 0); - } - } - - public void testExecStringCallback() throws Exception { - TableResult res = new TableResult(); - db.exec("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " VALUES(1, 10, 20)", null); - db.exec("select * from " + DatabaseCreator.SIMPLE_TABLE1, res); - db.exec("delete from " + DatabaseCreator.SIMPLE_TABLE1 + " where 1", null); - String row[] = (String[]) res.rows.elementAt(0); - assertEquals(Integer.parseInt(row[0]), 1); - assertEquals(Integer.parseInt(row[1]), 10); - assertEquals(Integer.parseInt(row[2]), 20); - } - - public void testExecStringCallbackStringArray() throws Exception { - TableResult res = new TableResult(); - String args[] = new String[1]; - args[0] = "table"; - db.exec("select name from sqlite_master where type = '%q';", res, args); - String[] s = (String[]) res.rows.elementAt(0); - assertEquals(s[0], DatabaseCreator.SIMPLE_TABLE1); - - try { - db.exec("select name from sqlite_master where type = ", res, args); - fail("Testmethod should fail"); - } catch (Exception e) { - // Ok - } - } - - public void testLast_insert_rowid() throws Exception { - assertEquals(0, db.last_insert_rowid()); - db.exec("create table TEST5(id integer, firstname text, lastname text);", null); - db.exec("insert into TEST5 values (1,'James','Bond');", null); - db.exec("insert into TEST5 values (2,'Fiona','Apple');", null); - assertEquals(2, db.last_insert_rowid()); - assertEquals(db.last_insert_rowid(), db.last_insert_rowid()); - - db.exec("drop table TEST5;", null); - assertEquals(2, db.last_insert_rowid()); - } - - /** - * Reason for failure unknown: Database should be locked. Specification - * of interrupt is scarce. - */ - public void testInterrupt() throws Exception, SQLException { - ThreadPool threadPool = new ThreadPool(numThreads); - - // initialization - ResultSet userTabs; - userTabs = conn.getMetaData().getTables(null, null, null, null); - while (userTabs.next()) { - String tableName = userTabs.getString("TABLE_NAME"); - if (tableName.equals(DatabaseCreator.TEST_TABLE1)) { - statement.execute(DatabaseCreator.DROP_TABLE1); - } - } - db.exec(DatabaseCreator.CREATE_TABLE3, null); - db.exec(DatabaseCreator.CREATE_TABLE1, null); - - int id1 = numOfRecords - 3; - threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker)); - // should not be able to do any other insertions since task 1 holds lock - int id2 = numOfRecords + 3; - threadPool - .runTask(createTask2Interrupt(id2, dbFile.getPath(), tracker)); - - threadPool.join(); - - List<String> errors = tracker.getErrors(); - System.out.println("Last error: " + db.error_message()); - if (errors.size() > 0) { - assertEquals(errors.get(0), db.error_string(Constants.SQLITE_LOCKED)); - for (String s : errors) { - Logger.global.info("INTERRUPT Error: " + s); - } - - } else { - fail("Should have one exception: database should be locked."); - } - - // reset - db.exec("delete from " + DatabaseCreator.TEST_TABLE1 + " where 1", null); - db.exec("delete from " + DatabaseCreator.TEST_TABLE3 + " where 1", null); - } - - /** - * Returns wrong number for updates: returns value > 1 for select. - */ - public void testChanges() throws Exception { - TableResult res = new TableResult(); - assertTrue(db.changes() == 0); - db.exec("INSERT INTO " + DatabaseCreator.SIMPLE_TABLE1 - + " VALUES(2, 5, 7);", null); - int rows = (int) db.changes(); - assertEquals(1,db.changes()); - db.exec("update " + DatabaseCreator.SIMPLE_TABLE1 - + " set speed = 7, size= 5 where id = 2;", null); - assertEquals(1,db.changes()); - db.exec("select * from " + DatabaseCreator.SIMPLE_TABLE1, res); - assertEquals(0,db.changes()); - db.exec("INSERT INTO " + DatabaseCreator.SIMPLE_TABLE1 - + " VALUES(8, 5, 7);", null); - db.exec("Update "+DatabaseCreator.SIMPLE_TABLE1+" set speed = 10;",null); - assertTrue(db.changes() > 2); - } - - /** - * method test fails once in a while. Cannot be sure that exception is - * thrown in every test execution. - */ - public void testBusy_handler() throws SQLException, Exception { - TestBusyHandler bh = new TestBusyHandler(); - db.busy_handler(bh); - int counter = 0; - ThreadPool threadPool = new ThreadPool(numThreads); - - // initialization - ResultSet userTabs; - userTabs = conn.getMetaData().getTables(null, null, null, null); - while (userTabs.next()) { - String tableName = userTabs.getString("TABLE_NAME"); - if (tableName.equals(DatabaseCreator.TEST_TABLE1)) { - statement.execute(DatabaseCreator.DROP_TABLE1); - } - } - db.exec(DatabaseCreator.CREATE_TABLE3, null); - db.exec(DatabaseCreator.CREATE_TABLE1, null); - - - try { - conn.setAutoCommit(false); - int id1 = numOfRecords - 3; - threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker)); - int id2 = numOfRecords + 3; - threadPool.runTask(createTask2(id2, dbFile.getPath(), tracker)); - int oldID = 5; - int newID = 100; - threadPool.runTask(createTask3(oldID, dbFile.getPath(), newID, - tracker)); - - threadPool.join(); - - List<String> errors = tracker.getErrors(); - if (errors.size() > 0) { -// assertEquals(errors.get(0), -// db.error_string(Constants.SQLITE_LOCKED)); - for (String s: errors) { - System.out.println("Round 2 Error: "+s); - } - } else { - fail("No error happened"); - } - - // reset - - - db.exec("delete from " + DatabaseCreator.TEST_TABLE1 + " where 1", - null); - db.exec("delete from " + DatabaseCreator.TEST_TABLE3 + " where 1", - null); -// -// // increase timeout for retry -// db.busy_timeout(1000); -// db.busy_handler(bh); -// tracker.reset(); - -// threadPool = new ThreadPool(numThreads); -// -// threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker)); -// threadPool.runTask(createTask2(id2, dbFile.getPath(), tracker)); -// -// threadPool.join(); -// -// errors = tracker.getErrors(); -// if (errors.size() > 0) { -// // assertEquals(errors.get(0), -// // db.error_string(Constants.SQLITE_LOCKED)); -// for (String s: errors) { -// System.out.println("Round 2 Error"+s); -// } -// } else { -// // ok -// System.out.println("BUSY: No Error!"); -// } -// -// - } finally { - conn.setAutoCommit(true); - db.exec(DatabaseCreator.DROP_TABLE1, null); - db.exec(DatabaseCreator.DROP_TABLE3, null); - } - } - - /** - * test fails. Cannot be sure that exception is thrown every time. - * Database does not lock values. - */ - public void testBusy_timeout() throws Exception, SQLException { - int counter = 0; - ThreadPool threadPool = new ThreadPool(numThreads); - - // initialization - ResultSet userTabs = conn.getMetaData().getTables(null, null, null, null); - while (userTabs.next()) { - String tableName = userTabs.getString("TABLE_NAME"); - if (tableName.equals(DatabaseCreator.TEST_TABLE1)) { - statement.execute(DatabaseCreator.DROP_TABLE1); - } - } - db.exec(DatabaseCreator.CREATE_TABLE3, null); - db.exec(DatabaseCreator.CREATE_TABLE1, null); - - // test run - try { - conn.setAutoCommit(false); - -// DatabaseCreator.fillTestTable1(conn, numOfRecords); - // set to fail immediately if table is locked. - db.busy_handler(null); - db.busy_timeout(0); - int id1 = numOfRecords - 3; - - threadPool.runTask(createTask2(id1, dbFile.getPath(), tracker)); - int id2 = numOfRecords + 3; - threadPool.runTask(createTask1(id2, dbFile.getPath(), tracker)); - int oldID = 5; - int newID = 100; - threadPool.runTask(createTask3(oldID, dbFile.getPath(), newID, - tracker)); - - threadPool.join(); - - List<String> errors = tracker.getErrors(); - assertTrue("No error occurred on DB but should have",errors.size() > 0); - - assertEquals(errors.get(0), - db.error_string(Constants.SQLITE_LOCKED)); - assertEquals(errors.get(0), "database is locked"); - - // reset - - db.exec("delete from " + DatabaseCreator.TEST_TABLE1 + " where 1", - null); - db.exec("delete from " + DatabaseCreator.TEST_TABLE3 + " where 1", - null); - - // increase timeout for retry - db.busy_timeout(10000); - db.busy_handler(null); - tracker.reset(); - threadPool = new ThreadPool(numThreads); - - threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker)); - threadPool.runTask(createTask2(id2, dbFile.getPath(), tracker)); - - threadPool.join(); - - errors = tracker.getErrors(); - if (errors.size() > 0) { - fail("busy timeout should prevent from lock exception!"); - for (String s: errors) { - System.out.println("Round 2 Error"+s); - } - } else { - // ok - } - } finally { - conn.setAutoCommit(true); - // cleanup - db.exec(DatabaseCreator.DROP_TABLE1, null); - db.exec(DatabaseCreator.DROP_TABLE3, null); - } - } - - public void testGet_tableString() throws Exception { - TableResult emptyTable = new TableResult(); - //select from empty table - TableResult res = db.get_table("select * from " + DatabaseCreator.SIMPLE_TABLE1); - assertEquals(res.toString(), emptyTable.toString()); - //fill table-> t -// DatabaseCreator.fillSimpleTable1(conn); -// res = db.get_table("select * from " -// + DatabaseCreator.SIMPLE_TABLE1); -// assertFalse(emptyTable.toString().equals(res.toString())); - - db.exec("insert into " + DatabaseCreator.SIMPLE_TABLE1 + " VALUES(1, 10, 20)", null); - res = db.get_table("select * from " + DatabaseCreator.SIMPLE_TABLE1); - db.exec("delete from " + DatabaseCreator.SIMPLE_TABLE1 - + " where 1", null); - String row[] = (String[]) res.rows.elementAt(0); - assertEquals(Integer.parseInt(row[0]), 1); - assertEquals(Integer.parseInt(row[1]), 10); - assertEquals(Integer.parseInt(row[2]), 20); - } - - public void testGet_tableStringStringArray() throws Exception { - String args[] = new String[1]; - args[0] = "table"; - String argsFail[] = new String[1]; - try { - db.get_table("select name from sqlite_master where type = ", argsFail); - fail("Testmethod should fail"); - } catch (Exception e) { - } - - TableResult res = db.get_table( - "select name from sqlite_master where type = '%q'", - args); - String[] s = (String[]) res.rows.elementAt(0); - assertEquals(s[0], DatabaseCreator.SIMPLE_TABLE1); - } - - public void testGet_tableStringStringArrayTableResult() throws Exception { - String args[] = new String[1]; - String argsFail[] = new String[1]; - TableResult res = new TableResult(); - TableResult defaultTableRes = new TableResult(); - args[0] = "table"; - - try { - db.get_table("select name from sqlite_master where type = '%q'", argsFail, res); - assertEquals(defaultTableRes.toString(), res.toString()); - } catch (Exception e) { - db.get_table("select name from sqlite_master where type = '%q'", args, res); - String[] s = (String[]) res.rows.elementAt(0); - assertEquals(s[0], DatabaseCreator.SIMPLE_TABLE1); - System.out.println("DatabaseTest.testGet_tableStringStringArrayTableResult() " - + Arrays.toString(res.types)); - } - } - - public void testComplete() { - assertFalse(db.complete("create")); - assertTrue(db.complete("create table TEST (res double);")); - } - - public void testVersion() { - String version = db.version(); - if (version != null) { - assertTrue(Integer.parseInt(db.version().substring(0, 1)) > 0); - assertEquals(db.version(), db.version()); - } else { - fail("DB version info missing"); - } - } - - public void testDbversion() throws Exception { - String verNo = ""; - try { - verNo = db.dbversion(); - db.close(); - assertEquals(db.dbversion(),"unknown"); - db.open(dbFile.getPath(), 0); - assertEquals(verNo, db.dbversion()); - } catch (Exception e) { - db.open(dbFile.getPath(), 0); - } - - assertTrue(Integer.parseInt(verNo.substring(0, 1))>= 3 ); - - } - - public void testCreate_function() throws Exception { - double input = 1.0; - db.exec("create table TEST (res double)", null); - db.exec("insert into TEST values (" + Double.toString(input) + ")", - null); - TableResult res = new TableResult(); - Function sinFunc = (Function) new SinFunc(); - db.create_function("sin", 1, sinFunc); - db.exec("select sin(res) from TEST WHERE res = " - + Double.toString(input), res); - String row[] = (String[]) res.rows.elementAt(0); - String val = row[0]; - double sinusVal = Double.parseDouble(val); - double funcVal = Math.sin(input); - - assertTrue(Math.round(funcVal) == Math.round(sinusVal)); - } - - /** - * Aggregation function not called. - */ - public void testCreate_aggregate() throws Exception { - TestTrace t = new TestTrace(); - MockFunction aggFunction = new MockFunction(); - db.exec("create table TEST(id integer, firstname text, lastname text)", null); - db.exec("insert into TEST values(3, 'James', 'Bond'); ", null); - db.exec("insert into TEST values(4, 'Fiona', 'Apple'); ", null); - db.trace((Trace) t); - db.create_aggregate("myaggfunc", 1, aggFunction); - db.function_type("myaggfunc", Constants.SQLITE3_TEXT); - db.exec("PRAGMA show_datatypes = on", null); - - assertFalse(aggFunction.functionCalled); - assertFalse(aggFunction.stepCalled); - assertFalse(aggFunction.lastStepCalled); - db.exec("select myaggfunc(TEST.firstname) from TEST", t); - assertTrue(aggFunction.stepCalled); - assertTrue(aggFunction.lastStepCalled); - assertTrue(aggFunction.functionCalled); - - assertEquals("James Fiona ",aggFunction.getAggValue()); - db.exec("drop table TEST", null); - - try { - db.create_aggregate("myaggfunc", 0, null); - } catch (Throwable e) { - assertEquals("null SQLite.Function not allowed",e.getMessage()); - } - - try { - db.create_aggregate("myaggfunc", 0, aggFunction); - } catch (Throwable e) { - assertEquals("wrong number of arguments to function myaggfunc()",e.getMessage()); - } - } - - public void testFunction_type() throws Exception { - double input = 1.0; - TableResult res = new TableResult(); - Function sinFunc = (Function) new SinFunc(); - - db.exec("PRAGMA show_datatypes = on", null); - db.exec("create table TEST (res double)", null); - db.exec("insert into TEST values (" + Double.toString(input) + ")", - null); - - db.create_function("sin", 1, sinFunc); - db.function_type("sin", Constants.SQLITE_FLOAT); - res = db.get_table("select sin(res) from TEST WHERE res = " - + Double.toString(input)); - - String row[] = (String[]) res.rows.elementAt(0); - String val = row[0]; - assertTrue("double".equalsIgnoreCase(res.types[0])); - assertSame(Math.round(Math.sin(input)), Math.round(Double.parseDouble(val))); - - // function determines return type: test that Double type is returned. - db.function_type("sin", Constants.SQLITE_BLOB); - Stmt s = db.prepare("select sin(res) from TEST WHERE res = ?"); - s.bind(1, input); - s.step(); - - res = db.get_table("select sin(res) from TEST WHERE res = " - + Double.toString(input)); - assertTrue("double".equalsIgnoreCase(res.types[0])); - row = (String[]) res.rows.elementAt(0); - val = row[0]; - assertSame(Math.round(Math.sin(input)), Math.round(Double.parseDouble(val))); - } - - public void testLast_error() { - assertEquals(db.last_error(), Constants.SQLITE_OK); - try { - db.exec("create table TEST (res double)",null); - db.exec("create table TEST (res double)",null); - fail("Error should have happened"); - } catch (Exception e) { - assertEquals(db.last_error(),db.last_error()); - assertEquals(db.last_error(),Constants.SQLITE_ERROR); - } - } - - public void testSet_last_error() { - assertEquals(db.last_error(), Constants.SQLITE_OK); - try { - db.exec("sel from test;", null); - } catch (Exception e) { - assertEquals(Constants.SQLITE_ERROR,db.last_error()); - } - } - - public void testError_message() { - String statement = "create table TEST (res double)"; - try { - db.exec(statement,null); - db.exec(statement,null); - fail("DB Error expected"); - } catch (Exception e) { - String dbError = db.error_message(); - assertTrue(e.getMessage().equals(dbError)); - - } - } - - public void testError_string() { - TestTrace t = new TestTrace(); - assertEquals(db.last_error(), Constants.SQLITE_OK); - String errorString = db.error_string(Constants.SQLITE_ERROR); - try { - db.trace((Trace) t); - db.exec("create table TEST (res double)", t); - db.exec("create table TEST (res double)", t); - } catch (Exception e) { - assertEquals(db.last_error(), Constants.SQLITE_ERROR); - if (db.is3()) { - assertEquals("Unsupported Method (sqlite 3): error_string", db - .error_string(db.last_error()), errorString); - } - } - } - - /** - * ASCII encoding does not work: a UTF encoded val is returned. Spec is not - * sufficient. Might be that test impl is wrong or String constructor for - * the ASCII encoding. - */ - public void testSet_encoding() throws UnsupportedEncodingException, Exception { - String input = "\u00bfMa\u00f1ana\u003f"; // ?Manana? - TableResult res = new TableResult(); - String refOutput = null; - Stmt stat = null; - - // DB setup - db.exec("create table encodingTest (encoded text DEFAULT NULL);", - null); - stat = db - .prepare("insert into encodingTest(encoded) values(:one);"); - stat.bind(1, input); - stat.step(); - // stat.close(); - db.exec("select * from encodingTest;", res); - String[] encInput = (String[]) res.rows.elementAt(0); - String output = encInput[0]; - assertEquals(input, output); - // db.exec("delete from encodingTest where 1", null); - - // tests for different encoding schemes - String[] charsetNames = {"UTF-8", "UTF-16", "UTF-16BE", "UTF-16LE"}; - for (int i = 0; i < charsetNames.length; i++) { - byte[] encInputBytes = input.getBytes(charsetNames[i]); - db.set_encoding(charsetNames[i]); - db.exec("select * from encodingTest;", res); - String[] encOutput = (String[]) res.rows.elementAt(0); - String inputAsString = new String(encInputBytes,charsetNames[i]); - assertEquals(inputAsString, encOutput[0]); - } - - // Default tests - db.set_encoding("UTF-16"); - db.exec("select * from encodingTest;", res); - String[] encOutput1 = (String[]) res.rows.elementAt(0); - assertEquals("Got "+encOutput1[0]+" as UTF-16",input,encOutput1[0]); - - db.set_encoding("US-ASCII"); - db.exec("select * from encodingTest;", res); - String[] encOutput2 = (String[]) res.rows.elementAt(0); - assertEquals(new String(input.getBytes(),"US-ASCII"),encOutput2[0]); - - // DB teardown - stat.close(); - db.exec("delete from encodingTest", null); - - // Default tests - try { - db.set_encoding(""); - fail("invalid input should fail"); - } catch (Exception e) { - //ok - } - } - - /** - * Callback never made for authorization. Results of private table are - * returned withouth furhter checks. - * - * Test fails -> implemented correctly? - */ - public void testSet_authorizer() throws Exception { - TableResult resPriv = null; - TableResult resPub = null; - TableResult emptyTable = new TableResult(); - String insertPublic = "insert into public_table values(1,2)"; - String insertPrivate = "insert into private_table values(1,2)"; - // prepare, authorizer is not activated yet - db.exec("create table public_table(c1 integer, c2 integer);", null); - db.exec("create table private_table(c1 integer, c2 integer);", null); - // inserts - db.exec(insertPublic, null); - db.exec(insertPrivate, null); - // selects - resPriv = db.get_table("select * from private_table"); - resPub = db.get_table("select * from public_table"); - -// db.exec("delete from public_table where 1", null); -// TableResult emptyPubTable = db.exec("select * from public"); - - // set Authorizer (positive case): denies private table - AuthorizerCallback cb = new AuthorizerCallback(); - db.set_authorizer(cb); - //select - - db.exec("select * from private_table", cb); - assertTrue(cb.wasCalled()); - - /* - TableResult res = db.get_table("select * from private_table"); - assertEquals(emptyTable.toString(),res.toString()); - assertFalse(emptyTable.equals(resPriv)); - - res = db.get_table("select * from public_table"); - assertEquals(resPub,res); - */ - - // Try insert - try { - db.exec(insertPublic, null); - fail("authorization failed"); - } catch (Exception e) { - } - - try { - db.exec(insertPrivate, null); - fail("authorization failed"); - } catch (Exception e1) { - // ok - } - } - - public void testTrace() throws Exception { - String stmt = "create table TEST (res double);"; - TestTrace t = new TestTrace(); - assertFalse(t.traceCalled); - assertEquals(db.last_error(),Constants.SQLITE_OK); - db.trace((Trace) t); - db.exec(stmt,t); - assertTrue(t.traceCalled); - assertEquals(t.getTrace(),stmt); - - try { - db.close(); - db.exec(stmt,t); - fail("Exception Expected"); - } catch (Exception e) { - //ok - } - } - - public void testCompileString() throws Exception { - db.compile("select name from sqlite_master;"); - try { - db.compile("test"); - fail("Compiling of inaccurate statement does not fail."); - } catch (Exception e) { - } - } - - public void testCompileStringStringArray() throws Exception { - String args[] = new String[1]; - args[0] = "table"; - db.compile("select name from sqlite_master where type = '%q';",args); - - try { - db.compile("test",null); - fail("Compiling of inaccurate statement does not fail."); - } catch (Exception e) { - } - } - - public void testPrepare() throws Exception { - Stmt st = null; - Stmt st2 = null; - // test empty statement - try { - st = db.prepare(""); - assertEquals(0, st.bind_parameter_count()); - st.step(); - fail("stmt should not be prepared"); - } catch (Exception e) { - assertEquals("stmt already closed", e.getMessage()); - } - - // test statement with unbound arguments - try { - st2 = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (:one,:two,:three)"); - assertEquals(3, st2.bind_parameter_count()); - assertEquals(3, st2.bind_parameter_index(":three")); - assertEquals(":two", st2.bind_parameter_name(2)); - } finally { - st2.close(); - } - - try { - db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values(:one,:two,:three,:four);"); - } catch (Exception e) { - assertEquals("table " + DatabaseCreator.SIMPLE_TABLE1 - + " has 3 columns but 4 values were supplied", e - .getMessage()); - } - - try { - db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values(5, '10, 20);"); - } catch (Exception e) { - assertEquals("unrecognized token: \"'10, 20);\"", e.getMessage()); - } - - try { - db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values(5, 10 20);"); - } catch (Exception e) { - assertEquals("near \"20\": syntax error", e.getMessage()); - } - - } - - /** - * Not supported. - */ - public void testOpen_blob() throws Exception, java.lang.Exception { - Stmt statement2; - Blob blobInput = new Blob(); - - // Create test input Blob - InputStream inStream = null; - byte[] in = {(byte) 1, (byte) 2, (byte) 3, (byte) 4}; - - // setup test input - db.exec("create table TEST (res blob)",null); - inStream = Class.forName(this.getClass().getName()).getResourceAsStream("/blob.c"); - assertNotNull(inStream); - - // insert byte array in db - statement2 = db.prepare("insert into TEST(res) values (?)"); - statement2.bind(1, in); - statement2.step(); - statement2.close(); - - // read from db - Blob blob = db.open_blob(dbFile.getPath(), "TEST", "res", 1, true); - if (blob == null) { - fail("Blob could not be retrieved"); - } - //read from blob and compare values (positive case) - InputStream is = blob.getInputStream(); - - int i = 0; - int outByte = 0; - byte[] out = new byte[4]; - while ((outByte = is.read()) > -1) { - out[i] = (byte) outByte; - i++; - } - is.close(); - - blob.close(); - - assertTrue(Arrays.equals(in, out)); - - //read from blob and compare values (default blob) - db.exec("insert into TEST values(zeroblob(128))", null); - Blob blob2 = db.open_blob(dbFile.getPath(), "TEST", "res", 2, true); - is = blob2.getInputStream(); - for (i = 0; i < 128; i++) { - assertEquals(0, is.read()); - } - is.close(); - } - - public void testIs3() { - int ver = Integer.parseInt(db.version().substring(0,1)); - if (db.is3()) { - assertTrue( ver == 3); - } else { - assertTrue(ver != 3); - } - } - - public void testProgress_handler() throws Exception { - int inputVal = 3; - TestProgressHandler prog = new TestProgressHandler(); - db.exec("create table TEST5(id integer, firstname text, lastname text)",null); - Vm vm = db.compile("select * from TEST5; " - + "insert into TEST5 values(3, 'James', 'Bond'); " - + "delete from TEST5 where id = 3; " - + "select * from TEST5"); - int stmt = 0; - do { - ++stmt; - if (stmt > inputVal) { - db.progress_handler(inputVal, prog); - } else { - assertEquals(0, prog.getCounts()); - } - while (vm.step(prog)) { - } - } while (vm.compile()); - assertEquals(inputVal,prog.getCounts()); - - // Boundary value test - inputVal = 0; - TestProgressHandler progBoundary = new TestProgressHandler(); - db.progress_handler(inputVal, progBoundary); - Vm vm2 = db.compile("select * from TEST5; " - + "insert into TEST5 values(3, 'James', 'Bond'); " - + "delete from TEST5 where id = 3; " - + "select * from TEST5"); - do { - vm2.step(progBoundary); - } while (vm2.compile()); - assertEquals(inputVal, progBoundary.getCounts()); - - try { - db.exec("drop table TEST5",null); - } catch (Exception e) { - System.out.println(e.getMessage()); - e.printStackTrace(); - } - } - - class SinFunc implements Function { - public void function(FunctionContext fc, String args[]) { - Double d = new Double(args[0]); - fc.set_result(Math.sin(d.doubleValue())); - } - public void last_step(FunctionContext fc) {} - public void step(FunctionContext fc, String[] args) {} - } - - class TestTrace implements Trace,Callback { - - private StringBuffer buf = new StringBuffer(); - - public boolean traceCalled = false; - - public String getTrace() { - return buf.toString(); - } - - public void trace(String stmt) { - traceCalled = true; - buf.append(stmt); - } - - public void columns(String[] coldata) {} - - public boolean newrow(String[] rowdata) { - return false; - } - - public void types(String[] types) {} - } - - class AuthorizerCallback implements Authorizer, Callback { - - private boolean isAuthorizing = false; - - public boolean wasCalled() { - return isAuthorizing; - } - - public int authorize(int action, String arg1, String arg2, String arg3, - String arg4) { - Logger.global.info("DB authorization callback " + action + " " + arg1 + " " + arg2 + " " - + arg3 + " " + arg4 + " "); - this.isAuthorizing = true; - if (action != Constants.SQLITE_SELECT || arg1.contains("private_table")) { - return Constants.SQLITE_DENY; - } else { - return Constants.SQLITE_OK; - } - } - - public void columns(String[] coldata) {} - - public boolean newrow(String[] rowdata) { - return false; - } - - public void types(String[] types) {} - - } - - class TestBusyHandler implements BusyHandler, Callback { - - public boolean busy(String table, int count) { - return true; - } - - public void columns(String[] coldata) {} - - public boolean newrow(String[] rowdata) { - return false; - } - - public void types(String[] types) {} - } - - class TestProgressHandler implements ProgressHandler, Callback { - - private boolean progressed = false; - - private int counter = 0; - - public int getCounts() { - return counter; - } - - public boolean progress() { - this.progressed = true; - counter++; - return true; - } - - public void columns(String[] coldata) {} - - public boolean newrow(String[] rowdata) { - return false; - } - - public void types(String[] types) {} - } - - /** - * This method creates a Runnable that executes insert operation for the first table - */ - private static Runnable createTask2Interrupt(final int id, - final String dbName, final ErrorTracker errorTracker) { - return new Runnable() { - public void run() { - Database db = new Database(); - try { - String value = DatabaseCreator.defaultString + id; - - db.open(dbName, 0); - String insertQuery = "INSERT INTO " - + DatabaseCreator.TEST_TABLE1 - + " (id, field1, field2, field3) VALUES(" + id - + ", '" + value + "', " + id + ", " + id + ")"; - db.exec(insertQuery, null); - } catch (Exception e) { - errorTracker.registerException(this, e); - try { - db.interrupt(); - db.exec("DELETE FROM " + DatabaseCreator.SIMPLE_TABLE1 - + " WHERE id=" + id, null); - } catch (Exception e1) { - errorTracker.registerException(this, e1); - } - } - } - }; - } - - /** - * This method creates a Runnable that executes delete operation for the first table - */ - private static Runnable createTask1(final int id, final String dbName, - final ErrorTracker errorTracker) { - return new Runnable() { - public void run() { - try { - Database db = new Database(); - db.open(dbName, 0); - db.exec("DELETE FROM " - + DatabaseCreator.SIMPLE_TABLE1 + " WHERE id=" + id, null); - } catch (Exception e) { - errorTracker.registerException(this, e); - } - } - }; - } - - /** - * This method creates a Runnable that executes insert operation for the first table - */ - private static Runnable createTask2(final int id, final String dbName, - final ErrorTracker errorTracker) { - return new Runnable() { - public void run() { - try { - String value = DatabaseCreator.defaultString + id; - Database db = new Database(); - db.open(dbName, 0); - String insertQuery = "INSERT INTO " - + DatabaseCreator.TEST_TABLE1 - + " (id, field1, field2, field3) VALUES(" + id - + ", '" + value + "', " + id + ", " + id + ")"; - db.exec(insertQuery, null); - } catch (Exception e) { - errorTracker.registerException(this, e); - - } - } - }; - } - - /** - * This method creates a Runnable that executes update operation for the one record of the first - * table - */ - private static Runnable createTask3(final int oldID, final String dbName, - final int newID, final ErrorTracker errorTracker) { - return new Runnable() { - public void run() { - Database db = new Database(); - try { - db.open(dbName, 0); - String value = DatabaseCreator.defaultString + newID; - String updateQuery = "UPDATE " - + DatabaseCreator.TEST_TABLE1 + " SET id=" + newID - + ", field1='" + value + "', field2=" + newID - + ", field3=" + newID + " WHERE id=" + oldID; - db.exec(updateQuery, null); - } catch (Exception e) { - errorTracker.registerException(this, e); - } - } - }; - } - - private class ErrorTracker { - - private List<String> errors = new ArrayList<String>(); - - public void registerException(Runnable runnable, Exception e) { - System.out.println("Registered: " + e.getMessage()); - errors.add(e.getMessage()); - } - - public List<String> getErrors() { - return errors; - } - - public void reset() { - errors.clear(); - } - } -} diff --git a/luni/src/test/java/libcore/sqlite/OldFunctionContextTest.java b/luni/src/test/java/libcore/sqlite/OldFunctionContextTest.java deleted file mode 100644 index 0924317..0000000 --- a/luni/src/test/java/libcore/sqlite/OldFunctionContextTest.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * Copyright (C) 2008 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.sqlite; - -import SQLite.Database; -import SQLite.Exception; -import SQLite.Function; -import SQLite.FunctionContext; -import SQLite.Stmt; -import SQLite.TableResult; -import java.io.UnsupportedEncodingException; -import java.sql.SQLException; -import java.sql.Statement; -import tests.support.DatabaseCreator; - -public final class OldFunctionContextTest extends OldSQLiteTest { - - private Database db = null; - - @Override public void setUp() throws java.lang.Exception { - super.setUp(); - db = new Database(); - db.open(dbFile.getPath(), 0); - Statement st = conn.createStatement(); - st.execute(DatabaseCreator.CREATE_TABLE2); - st.execute(DatabaseCreator.CREATE_TABLE_SIMPLE1); - st.close(); - } - - public void testSet_resultString() throws Exception { - TestFCString testString = new TestFCString(); - db.exec("insert into " + DatabaseCreator.TEST_TABLE2 - + " (ftext) values ('TestInput')", null); - db.create_function("test", 1, testString); - TableResult res = db.get_table("select test(ftext) from " - + DatabaseCreator.TEST_TABLE2); - String row[] = (String[]) res.rows.elementAt(0); - String val = row[0]; - - assertEquals("TestInput", val); - } - - public void testSet_resultInt() throws Exception { - TestFCInt testInt = new TestFCInt(); - db.exec("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (1,'" + testInt.intVal + "',3)", null); - db.create_function("testInt", 1, testInt); - TableResult res = db.get_table("select testInt(speed) from " - + DatabaseCreator.SIMPLE_TABLE1); - String row[] = (String[]) res.rows.elementAt(0); - String val = row[0]; - - assertEquals(testInt.intVal, Integer.parseInt(val)); - } - - public void testSet_resultDouble() throws Exception { - SinFunc testD = new SinFunc(); - db.exec("insert into " + DatabaseCreator.TEST_TABLE2 - + " (fdouble) values (" + testD.testDouble + ")", null); - db.create_function("testDouble", 1, testD); - TableResult res = db.get_table("select testDouble(fdouble) from " - + DatabaseCreator.TEST_TABLE2); - String row[] = (String[]) res.rows.elementAt(0); - String val = row[0]; - - assertEquals(testD.testDouble, Double.parseDouble(val)); - - assertTrue(testD.functionCalled); - } - - public void testSet_error() throws Exception { - TestFCError testError = new TestFCError(); - SinFunc testD = new SinFunc(); - db.exec("insert into " + DatabaseCreator.TEST_TABLE2 - + " (fdouble) values (" + testD.testDouble + ")", null); - db.create_function("testError", 1, testError); - - try { - TableResult res = db.get_table("select testError(fdouble) from " - + DatabaseCreator.TEST_TABLE2); - fail("Should get Exception"); - } catch (Exception e) { - assertEquals("error in step", e.getMessage()); - } - - assertFalse(testD.functionCalled); - } - - public void testSet_resultByteArray() throws Exception, UnsupportedEncodingException { - Stmt st = null; - TestFCByteArray testBinArrayFnc = new TestFCByteArray(); - String expected = ""; - expected = "X'" + getHexString(testBinArrayFnc.byteVal) + "'"; - - // setup - db.exec("create table testBinaryData (binVal BINARY) ;", null); - - try { - st = db.prepare("insert into testBinaryData values (?)"); - st.bind(1, testBinArrayFnc.byteVal); - st.step(); - - - db.create_function("testBinArray", 1, testBinArrayFnc); - TableResult res = db - .get_table("select testBinArray(binVal) from testBinaryData"); - - String row[] = (String[]) res.rows.elementAt(0); - String val = row[0]; - - assertTrue(expected.equalsIgnoreCase(val)); - - assertTrue(testBinArrayFnc.functionCalled); - - } finally { - //teardown - db.exec("drop table testBinaryData;", null); - } - } - - /** - * ZeroBlob not supported - */ - public void testSet_result_zeroblob() throws Exception, - UnsupportedEncodingException { - Stmt st = null; - TestFCZeroBlob testZeroBlobFnc = new TestFCZeroBlob(); - byte[] byteVal = {(byte) 1, (byte) 2, (byte) 3}; - - - // setup - db.exec("create table testBinaryData (binVal BINARY) ;", null); - - try { - st = db.prepare("insert into testBinaryData values (?)"); - st.bind(1, byteVal); - st.step(); - - - db.create_function("testZeroBlob", 0, testZeroBlobFnc); - TableResult res = db - .get_table("select testZeroBlob() from testBinaryData"); - TableResult res2 = db.get_table("select zeroblob(" - + testZeroBlobFnc.numBytes + ") from testBinaryData"); - - String row[] = (String[]) res.rows.elementAt(0); - String val = row[0]; - - assertNotNull(val); - - assertEquals(((String[]) res2.rows.elementAt(0))[0], val); - assertTrue(testZeroBlobFnc.functionCalled); - - } finally { - // teardown - db.exec("drop table if exists testBinaryData;", null); - } - } - - /** - * Test Method results in a segmentation fault - */ - public void testCount() throws SQLException, Exception { - TestFCCount countTest = new TestFCCount(); - int inputCount = 10; - - assertFalse(countTest.functionCalled); - - DatabaseCreator.fillTestTable2(conn, inputCount); - db.create_function("testCount", 0, countTest); - // the invokation of testCount leads to a Segmentation fault - /* - TableResult res = db - .get_table("select testCount() from "+DatabaseCreator.TEST_TABLE2); - - String row[] = (String[]) res.rows.elementAt(0); - String val = row[0]; - - assertTrue(countTest.functionCalled); - assertEquals(inputCount,Integer.parseInt(val)); - */ - - } - - class TestFCError implements Function { - public boolean functionCalled = false; - public String errorMsg = "FunctionError"; - - public void function(FunctionContext fc, String args[]) { - functionCalled = true; - fc.set_error(errorMsg); - } - - public void last_step(FunctionContext fc) {} - public void step(FunctionContext fc, String[] args) {} - } - - class TestFCCount implements Function { - public boolean functionCalled = false; - public int noOfRows = 0; - - public void function(FunctionContext fc, String args[]) { - functionCalled = true; - noOfRows = fc.count(); - fc.set_result(noOfRows); - } - - public void last_step(FunctionContext fc) {} - public void step(FunctionContext fc, String[] args) {} - } - - class TestFCZeroBlob implements Function { - public int numBytes = 16; - public boolean functionCalled = false; - - public void function(FunctionContext fc, String args[]) { - functionCalled = true; - fc.set_result_zeroblob(numBytes); - } - - public void last_step(FunctionContext fc) {} - public void step(FunctionContext fc, String[] args) {} - } - - class TestFCString implements Function { - public String testString = "TestString"; - public boolean functionCalled; - - public void function(FunctionContext fc, String args[]) { - assertNotNull(args); - functionCalled = true; - fc.set_result(args[0]); - } - - public void last_step(FunctionContext fc) {} - public void step(FunctionContext fc, String[] args) {} - } - - class TestFCInt implements Function { - public int intVal = Integer.MAX_VALUE; - public boolean functionCalled; - - public void function(FunctionContext fc, String args[]) { - assertNotNull(args); - functionCalled = true; - fc.set_result(Integer.parseInt(args[0])); - } - - public void last_step(FunctionContext fc) {} - public void step(FunctionContext fc, String[] args) {} - } - - class TestFCByteArray implements Function { - public byte[] byteVal = {(byte) 1, (byte) 2, (byte) 3}; - public boolean functionCalled; - - public void function(FunctionContext fc, String args[]) { - assertNotNull(args); - functionCalled = true; - fc.set_result(args[0].getBytes()); - } - - public void last_step(FunctionContext fc) {} - public void step(FunctionContext fc, String[] args) {} - } - - class SinFunc implements Function { - public Double testDouble = 3.0; - public boolean functionCalled = false; - - public void function(FunctionContext fc, String args[]) { - Double d = new Double(args[0]); - functionCalled = true; - fc.set_result(d.doubleValue()); - } - - public void last_step(FunctionContext fc) {} - public void step(FunctionContext fc, String[] args) {} - } - - static final byte[] HEX_CHAR_TABLE = { - (byte)'0', (byte)'1', (byte)'2', (byte)'3', - (byte)'4', (byte)'5', (byte)'6', (byte)'7', - (byte)'8', (byte)'9', (byte)'a', (byte)'b', - (byte)'c', (byte)'d', (byte)'e', (byte)'f' - }; - - public static String getHexString(byte[] raw) - throws UnsupportedEncodingException { - byte[] hex = new byte[2 * raw.length]; - int index = 0; - - for (byte b : raw) { - int v = b & 0xFF; - hex[index++] = HEX_CHAR_TABLE[v >>> 4]; - hex[index++] = HEX_CHAR_TABLE[v & 0xF]; - } - return new String(hex, "ASCII"); - } -} diff --git a/luni/src/test/java/libcore/sqlite/OldJDBCDriverFunctionalTest.java b/luni/src/test/java/libcore/sqlite/OldJDBCDriverFunctionalTest.java deleted file mode 100644 index 48eeab1..0000000 --- a/luni/src/test/java/libcore/sqlite/OldJDBCDriverFunctionalTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2007 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.sqlite; - -import java.io.File; -import java.io.IOException; -import java.sql.Connection; -import java.sql.SQLException; - -/** - * Tests the SQLite.JDBCDriver. - */ -public class OldJDBCDriverFunctionalTest extends AbstractSqlTest { - private File dbFile = null; - private String connectionURL = "empty"; - - @Override protected void tearDown() throws SQLException { - super.tearDown(); - dbFile.delete(); - } - - @Override protected String getConnectionURL() { - if (connectionURL.equals("empty")) { - String tmp = System.getProperty("java.io.tmpdir"); - File tmpDir = new File(tmp); - if (tmpDir.isDirectory()) { - try { - dbFile = File.createTempFile("JDBCDriverFunctionalTest", ".db", tmpDir); - } catch (IOException e) { - System.err.println("error creating temporary DB file."); - } - dbFile.deleteOnExit(); - } else { - System.err.println("java.io.tmpdir does not exist"); - } - - connectionURL = "jdbc:sqlite:/" + dbFile.getPath(); - } - - return connectionURL; - } - - @Override protected String getDriverClassName() { - return "SQLite.JDBCDriver"; - } - - @Override protected int getTransactionIsolation() { - return Connection.TRANSACTION_SERIALIZABLE; - } -} diff --git a/luni/src/test/java/libcore/sqlite/OldJDBCDriverTest.java b/luni/src/test/java/libcore/sqlite/OldJDBCDriverTest.java deleted file mode 100644 index ae06dc6..0000000 --- a/luni/src/test/java/libcore/sqlite/OldJDBCDriverTest.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (C) 2008 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.sqlite; - -import SQLite.JDBCDriver; -import java.sql.Connection; -import java.sql.Driver; -import java.sql.DriverManager; -import java.sql.DriverPropertyInfo; -import java.sql.SQLException; - - -public final class OldJDBCDriverTest extends OldJDBCDriverFunctionalTest { - - /** - * The SQLite db file. - */ - private JDBCDriver jDriver; - - private Driver returnedDriver; - - @Override public void setUp() throws java.lang.Exception { - super.setUp(); - returnedDriver = DriverManager.getDriver(getConnectionURL()); - if (returnedDriver instanceof JDBCDriver) { - this.jDriver = (JDBCDriver) returnedDriver; - } - } - - public void testJDBCDriver() { - assertTrue(returnedDriver instanceof JDBCDriver); - } - - public void testAcceptsURL() { - try { - if (this.jDriver != null) { - assertTrue(jDriver.acceptsURL(getConnectionURL())); - } else { - fail("no Driver available"); - } - } catch (SQLException e) { - fail("Driver does not accept URL"); - e.printStackTrace(); - } - } - - public void testConnect() { - try { - if (this.jDriver != null) { - Connection c = jDriver.connect(getConnectionURL(), null); - assertFalse(c.isClosed()); - DriverManager.getConnection(getConnectionURL()); - } else { - fail("no Driver available"); - } - } catch (SQLException e) { - fail("Driver does not connect"); - e.printStackTrace(); - } - } - - public void testGetMajorVersion() { - if (this.jDriver != null) { - assertTrue(jDriver.getMajorVersion() > 0); - } else { - fail("no Driver available"); - } - } - - public void testGetMinorVersion() { - if (this.jDriver != null) { - assertTrue(jDriver.getMinorVersion() > 0); - } else { - fail("no version information available"); - } - } - - public void testGetPropertyInfo() throws SQLException { - DriverPropertyInfo[] info = null; - if (this.jDriver != null) { - info = jDriver.getPropertyInfo(getConnectionURL(), null); - assertNotNull(info); - assertTrue(info.length > 0); - } else { - fail("no Driver available"); - } - - assertNotNull(info); - - } - - public void testJdbcCompliant() { - if (this.jDriver != null) { - assertFalse(jDriver.jdbcCompliant()); - } else { - fail("no version information available"); - } - } -} diff --git a/luni/src/test/java/libcore/sqlite/OldSQLiteTest.java b/luni/src/test/java/libcore/sqlite/OldSQLiteTest.java deleted file mode 100644 index e6b7f22..0000000 --- a/luni/src/test/java/libcore/sqlite/OldSQLiteTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2008 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.sqlite; - -import java.io.File; -import java.io.IOException; -import java.sql.Connection; -import java.sql.DriverManager; -import java.util.logging.Logger; -import junit.framework.TestCase; - -public abstract class OldSQLiteTest extends TestCase { - - public static Connection conn; - - public static File dbFile = null; - - @Override public void setUp() throws Exception { - String tmp = System.getProperty("java.io.tmpdir"); - File tmpDir = new File(tmp); - try { - if (tmpDir.isDirectory()) { - dbFile = File.createTempFile("sqliteTest", ".db", tmpDir); - dbFile.deleteOnExit(); - } else { - System.out.println("ctsdir does not exist"); - } - - Class.forName("SQLite.JDBCDriver").newInstance(); - - if (!dbFile.exists()) { - Logger.global.severe("DB file could not be created. Tests can not be executed."); - } else { - conn = DriverManager.getConnection("jdbc:sqlite:/" + dbFile.getPath()); - } - assertNotNull("Error creating connection", conn); - } catch (IOException e) { - System.out.println("Problem creating test file in " + tmp); - } - } - - @Override public void tearDown() throws java.lang.Exception { - if (!conn.isClosed()) { - conn.close(); - } - super.tearDown(); - } -} diff --git a/luni/src/test/java/libcore/sqlite/OldStmtTest.java b/luni/src/test/java/libcore/sqlite/OldStmtTest.java deleted file mode 100644 index 4d379ed..0000000 --- a/luni/src/test/java/libcore/sqlite/OldStmtTest.java +++ /dev/null @@ -1,823 +0,0 @@ -/* - * Copyright (C) 2008 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.sqlite; - -import SQLite.Constants; -import SQLite.Database; -import SQLite.Stmt; -import SQLite.TableResult; -import java.sql.Connection; -import tests.support.DatabaseCreator; -import tests.support.Support_SQL; - -public class OldStmtTest extends OldSQLiteTest { - - private Database db; - private Stmt st; - - private static final String CREATE_ALL_TYPES = "create table type (" - + " BoolVal BOOLEAN," - + " IntVal INT," - + " LongVal LONG," - + " Bint BIGINT," - + " Tint TINYINT," - + " Sint SMALLINT," - + " Mint MEDIUMINT," - + " IntegerVal INTEGER," - + " RealVal REAL," - + " DoubleVal DOUBLE," - + " FloatVal FLOAT," - + " DecVal DECIMAL," - + " NumVal NUMERIC," - + " charStr CHAR(20)," - + " dateVal DATE," - + " timeVal TIME," - + " TS TIMESTAMP," - + " DT DATETIME," - + " TBlob TINYBLOB," - + " BlobVal BLOB," - + " MBlob MEDIUMBLOB," - + " LBlob LONGBLOB," - + " TText TINYTEXT," - + " TextVal TEXT," - + " MText MEDIUMTEXT," - + " LText LONGTEXT," - + " MaxLongVal BIGINT," - + " MinLongVal BIGINT," - + " validURL URL," - + " invalidURL URL);"; - - static final String INSERT_ALL_TYPES = "insert into type (" - + "BoolVal, IntVal, LongVal, Bint, Tint, Sint, Mint,IntegerVal, RealVal, DoubleVal, " - + "FloatVal, DecVal,NumVal, charStr, dateVal, timeVal, TS,DT, TBlob, BlobVal, MBlob, " - + "LBlob,TText, TextVal, MText, LText, MaxLongVal, MinLongVal, validURL, invalidURL) " - + "values (1, -1, 22, 2, 33,3, 1, 2, 3.9, 23.2, 33.3, 44,5, 'test string', '1799-05-26'," - + "'12:35:45', '2007-10-09 14:28:02.0','1221-09-22 10:11:55', 1, 2, 3, 4," - + "'Test text message tiny', 'Test text', 'Test text message medium'," - + "'Test text message long', " + Long.MAX_VALUE + ", " + Long.MIN_VALUE + "," - + "null, null);"; - - static final String ALL_TYPES_TABLE = "type"; - - @Override public void setUp() throws Exception { - super.setUp(); - Support_SQL.loadDriver(); - db = new Database(); - db.open(dbFile.getPath(), 0); - db.exec(DatabaseCreator.CREATE_TABLE_SIMPLE1, null); - DatabaseCreator.fillSimpleTable1(conn); - - st = new Stmt(); - } - - @Override public void tearDown() throws Exception { - if (st != null) { - try { - st.close(); - } catch (Exception e) { - } - } - db.close(); - Connection con = Support_SQL.getConnection(); - con.close(); - super.tearDown(); - } - - public void testStmt() throws Exception { - db.prepare(""); - - try { - st.step(); - fail("Cannot execute non prepared Stmt"); - } catch (SQLite.Exception expected) { - } - } - - public void testPrepare() throws Exception { - try { - st = db.prepare(""); - st.prepare(); - fail("statement is closed"); - } catch (SQLite.Exception expected) { - assertEquals("stmt already closed", expected.getMessage()); - } - - st = new Stmt(); - st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1); - assertFalse(st.prepare()); - st = new Stmt(); - st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (:one,:two,:three)"); - assertFalse(st.prepare()); - st = new Stmt(); - st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (:one,:two,:three)"); - st.bind(1, 1); - st.bind(2, 10); - st.bind(3, 30); - assertFalse(st.prepare()); - st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1 - + "; " + "delete from " + DatabaseCreator.SIMPLE_TABLE1 - + " where id = 5; " + "insert into " - + DatabaseCreator.SIMPLE_TABLE1 + " values(5, 10, 20); " - + "select * from " + DatabaseCreator.SIMPLE_TABLE1 + ";"); - assertTrue(st.prepare()); - assertTrue(st.prepare()); - assertTrue(st.prepare()); - assertFalse(st.prepare()); - } - - public void testStep() throws Exception { - try { - st.step(); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - assertEquals("stmt already closed", expected.getMessage()); - } - - st = new Stmt(); - st = db.prepare("select name from sqlite_master where type = 'table'"); - st.step(); - } - - public void testClose() throws Exception { - st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (:one,:two,:three)"); - st.close(); - - try { - st.step(); - fail("Test fails"); - } catch (SQLite.Exception expected) { - assertEquals("stmt already closed", expected.getMessage()); - } - } - - public void testReset() throws Exception { - db.exec("create table TEST (res integer not null)", null); - - st = db.prepare("insert into TEST values (:one);"); - st.bind(1, 1); - st.step(); - - // verify that parameter is still bound - st.reset(); - assertEquals(1,st.bind_parameter_count()); - st.step(); - - TableResult count = db.get_table("select count(*) from TEST where res=1", null); - - String[] row0 = (String[]) count.rows.elementAt(0); - assertEquals(2, Integer.parseInt(row0[0])); - } - - public void testClear_bindings() { - try { - st.clear_bindings(); - } catch (SQLite.Exception expected) { - assertEquals("unsupported", expected.getMessage()); - } - } - - public void testBindIntInt() throws Exception { - int input = 0; - int maxVal = Integer.MAX_VALUE; - int minVal = Integer.MIN_VALUE; - - db.exec("create table TEST (res integer)", null); - st = db.prepare("insert into TEST values (:one);"); - st.bind(1, input); - st.step(); - - st.reset(); - st.bind(1,maxVal); - st.step(); - - st.reset(); - st.bind(1,minVal); - st.step(); - - TableResult r = db.get_table("select * from TEST"); - - String[] row0 = (String[]) r.rows.elementAt(0); - assertEquals(input,Integer.parseInt(row0[0])); - - String[] row1 = (String[]) r.rows.elementAt(1); - assertEquals(maxVal,Integer.parseInt(row1[0])); - - String[] row2 = (String[]) r.rows.elementAt(2); - assertEquals(minVal,Integer.parseInt(row2[0])); - - try { - st.close(); - st.bind(1,Integer.MIN_VALUE); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - } - } - - public void testBindIntLong() throws Exception { - long input = 0; - long maxVal = Long.MAX_VALUE; - long minVal = Long.MIN_VALUE; - - db.exec("create table TEST (res long)", null); - st = db.prepare("insert into TEST values (:one);"); - st.bind(1, input); - st.step(); - - st.reset(); - st.bind(1,maxVal); - st.step(); - - st.reset(); - st.bind(1,minVal); - st.step(); - - TableResult r = db.get_table("select * from TEST"); - - String[] row0 = (String[]) r.rows.elementAt(0); - assertEquals(input,Long.parseLong(row0[0])); - - String[] row1 = (String[]) r.rows.elementAt(1); - assertEquals(maxVal,Long.parseLong(row1[0])); - - String[] row2 = (String[]) r.rows.elementAt(2); - assertEquals(minVal,Long.parseLong(row2[0])); - - try { - st.close(); - st.bind(1,Long.MIN_VALUE); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - } - } - - public void testBindIntDouble() throws Exception { - double input = 0.0; - double maxVal = Double.MAX_VALUE; - double minVal = Double.MIN_VALUE; - double negInf = Double.NEGATIVE_INFINITY; - double posInf = Double.POSITIVE_INFINITY; - double nan = Double.NaN; - - db.exec("create table TEST (res double)", null); - st = db.prepare("insert into TEST values (:one);"); - st.bind(1, input); - st.step(); - - st.reset(); - st.bind(1, maxVal); - st.step(); - - st.reset(); - st.bind(1, minVal); - st.step(); - - st.reset(); - st.bind(1, negInf); - st.step(); - - st.reset(); - st.bind(1, posInf); - st.step(); - - st.reset(); - st.bind(1, nan); - st.step(); - - - TableResult r = db.get_table("select * from TEST"); - - String[] row0 = (String[]) r.rows.elementAt(0); - assertTrue(Double.compare(input, Double.parseDouble(row0[0])) == 0); - - String[] row1 = (String[]) r.rows.elementAt(1); - assertFalse(Double.compare(maxVal, Double.parseDouble(row1[0])) == 0); - assertTrue(Double.compare(maxVal, Double.parseDouble(row1[0])) < 0); - assertTrue(Double.isInfinite(Double.parseDouble(row1[0]))); - - String[] row2 = (String[]) r.rows.elementAt(2); - assertTrue(Double.compare(minVal, Double.parseDouble(row2[0])) == 0); - - String[] row3 = (String[]) r.rows.elementAt(3); - assertEquals("Double.NEGATIVE_INFINITY SQLite representation", - "-Inf", row3[0]); - - String[] row4 = (String[]) r.rows.elementAt(4); - assertEquals("Double.POSITIVE_INFINITY SQLite representation", - "Inf", row4[0]); - - String[] row5 = (String[]) r.rows.elementAt(4); - assertEquals("Double.Nan SQLite representation", "Inf", row5[0]); - - try { - st.close(); - st.bind(1,0.0); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - } - } - - public void testBindIntByteArray() throws Exception { - String name = "Hello World"; - byte[] b = name.getBytes(); - String stringInHex = ""; - - db.exec(DatabaseCreator.CREATE_TABLE_PARENT, null); - st = db.prepare("insert into " + DatabaseCreator.PARENT_TABLE - + " values (:one, :two);"); - st.bind(1, 2); - st.bind(2, b); - st.step(); - - //compare what was stored with input based on Hex representation - // since type of column is CHAR - TableResult r = db.get_table("select * from " - + DatabaseCreator.PARENT_TABLE); - String[] row = (String[]) r.rows.elementAt(0); - - for (byte aByte : b) { - stringInHex += Integer.toHexString(aByte); - } - stringInHex = "X'" + stringInHex + "'"; - assertTrue(stringInHex.equalsIgnoreCase(row[1])); - - try { - st.close(); - st.bind(1,name.getBytes()); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - } - } - - public void testBindIntString() throws Exception { - String name = "Hello World"; - db.exec(DatabaseCreator.CREATE_TABLE_PARENT, null); - st = db.prepare("insert into " + DatabaseCreator.PARENT_TABLE - + " values (:one, :two);"); - st.bind(1, 2); - st.bind(2, name); - st.step(); - - TableResult r = db.get_table("select * from " - + DatabaseCreator.PARENT_TABLE); - String[] row = (String[]) r.rows.elementAt(0); - assertEquals(name,row[1]); - - try { - st.close(); - st.bind(1,name); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - } - } - - public void testBindInt() throws Exception { - try { - st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (:one,:two,:three)"); - st.bind(4); - st.bind(1, 4); - st.bind(2, 10); - st.bind(3, 30); - st.step(); - fail(); - } catch (SQLite.Exception expected) { - // What happens if null is bound to non existing variable position - assertEquals("parameter position out of bounds", expected.getMessage()); - } - - // functional tests - - try { - st.reset(); - st.bind(1); - st.bind(2, 10); - st.bind(3, 30); - st.step(); - fail(); - } catch (SQLite.Exception expected) { - // What happens if null is bound to NON NULL field - assertEquals("SQL logic error or missing database", expected.getMessage()); - } - - st.reset(); - st.bind(1, 3); - st.bind(2); - st.bind(3, 30); - st.step(); - } - - public void testBind_zeroblob() { - try { - st.bind_zeroblob(1, 128); - fail(); - } catch (SQLite.Exception expected) { - assertEquals("unsupported", expected.getMessage()); - } - } - - public void testBind_parameter_count() throws Exception { - try { - st.bind_parameter_count(); - fail(); - } catch (SQLite.Exception expected) { - assertEquals("stmt already closed", expected.getMessage()); - } - - st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (:one,:two,:three)"); - assertEquals(3, st.bind_parameter_count()); - - st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (?, ?, ?)"); - assertEquals(3, st.bind_parameter_count()); - - st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1); - assertEquals(0, st.bind_parameter_count()); - - try { - st.close(); - st.bind_parameter_count(); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - } - - } - - public void testBind_parameter_name() { - try { - st.bind_parameter_name(1); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - assertEquals("stmt already closed", expected.getMessage()); - } - - try { - st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (:one,:two,:three)"); - assertEquals(":one", st.bind_parameter_name(1)); - assertEquals(":two", st.bind_parameter_name(2)); - assertEquals(":three", st.bind_parameter_name(3)); - st.bind_parameter_name(4); - fail(); - } catch (SQLite.Exception expected) { - assertEquals("parameter position out of bounds", expected.getMessage()); - } - } - - public void testBind_parameter_index() throws Exception { - try { - st.bind_parameter_index(""); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - assertEquals("stmt already closed", expected.getMessage()); - } - - st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (:one,:two,:three)"); - assertEquals(3, st.bind_parameter_index(":three")); - - st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (:one,:two,:three)"); - assertEquals(0, st.bind_parameter_index(":t")); - - st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (?, ?, ?)"); - assertEquals(0, st.bind_parameter_index("?")); - } - - public void testColumn_int() throws Exception { - db.exec(CREATE_ALL_TYPES, null); - db.exec(INSERT_ALL_TYPES, null); - - Object columnObject; - int intColumn; - String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1; - - st = db.prepare(selectStmt); - st.step(); - // select 'speed' value - columnObject = st.column(1); - intColumn = st.column_int(1); - assertNotNull(intColumn); - - assertTrue("Integer".equalsIgnoreCase(st.column_decltype(1))); - int stSpeed = Integer.parseInt(columnObject.toString()); - assertNotNull(stSpeed); - assertEquals( intColumn, stSpeed); - assertEquals(10,stSpeed); - - selectStmt = "select TextVal from "+ ALL_TYPES_TABLE; - - st = db.prepare(selectStmt); - st.step(); - st.column_int(0); - } - - public void testColumn_long() throws Exception { - Object columnObject; - long longColumn; - String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1; - st = db.prepare(selectStmt); - st.step(); - columnObject = st.column(1); - longColumn = st.column_long(1); - assertNotNull(longColumn); - // column declared as integer - assertTrue("Integer".equalsIgnoreCase(st.column_decltype(1))); - int stSpeed = Integer.parseInt(columnObject.toString()); - assertNotNull(stSpeed); - assertEquals( longColumn, stSpeed); - - try { - st.column_long(4); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - assertEquals("column out of bounds", expected.getMessage()); - } - - try { - st.column_long(-1); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - assertEquals("column out of bounds", expected.getMessage()); - } - } - - public void testColumn_double() throws Exception { - db.exec(CREATE_ALL_TYPES, null); - db.exec(INSERT_ALL_TYPES, null); - - double doubleColumn; - double actualVal = 23.2; - String selectStmt = "select DoubleVal from "+ ALL_TYPES_TABLE; - - st = db.prepare(selectStmt); - st.step(); - // select double value - doubleColumn = st.column_double(0); - assertNotNull(doubleColumn); - - assertTrue("DOUBLE".equalsIgnoreCase(st.column_decltype(0))); - assertNotNull(doubleColumn); - assertEquals( actualVal, doubleColumn); - - // Exception test - selectStmt = "select dateVal from "+ ALL_TYPES_TABLE; - - st = db.prepare(selectStmt); - st.step(); - // select double value - st.column_double(0); - } - - public void testColumn_bytes() throws Exception { - db.exec("create table B(id integer primary key, val blob)",null); - db.exec("insert into B values(1, zeroblob(128))", null); - st = db.prepare("select val from B where id = 1"); - assertTrue(st.step()); - st.column_bytes(0); - } - - public void testColumn_string() throws Exception { - db.exec(CREATE_ALL_TYPES, null); - db.exec(INSERT_ALL_TYPES, null); - - String stringColumn; - String actualVal = "test string"; - String selectStmt = "select charStr from "+ ALL_TYPES_TABLE; - - st = db.prepare(selectStmt); - st.step(); - // select string value - stringColumn = st.column_string(0); - assertNotNull(stringColumn); - - assertTrue("CHAR(20)".equalsIgnoreCase(st.column_decltype(0))); - assertNotNull(stringColumn); - assertEquals( actualVal, stringColumn); - - // Exception test - selectStmt = "select DoubleVal from "+ ALL_TYPES_TABLE; - - st = db.prepare(selectStmt); - st.step(); - st.column_string(0); - } - - public void testColumn_type() throws Exception { - db.exec(CREATE_ALL_TYPES, null); - db.exec(INSERT_ALL_TYPES, null); - st = db.prepare("select * from " + ALL_TYPES_TABLE); - st.step(); - - // Exception test - try { - st.column_type(100); - fail(); - } catch (SQLite.Exception expected) { - } - - /* - Dictionary - - public static final int SQLITE_INTEGER = 1; - public static final int SQLITE_FLOAT = 2; - public static final int SQLITE_BLOB = 4; - public static final int SQLITE_NULL = 5; - public static final int SQLITE3_TEXT = 3; - public static final int SQLITE_NUMERIC = -1; - */ - - assertEquals(Constants.SQLITE3_TEXT, st.column_type(23)); // ok TEXT - assertEquals(Constants.SQLITE3_TEXT, st.column_type(13)); // CHAR(20) - - assertEquals(Constants.SQLITE_FLOAT, st.column_type(8)); - assertEquals(Constants.SQLITE_FLOAT, st.column_type(9)); - assertEquals(Constants.SQLITE_FLOAT, st.column_type(10)); // FLOAT - - for (int i = 0; i < 8; i++) { - assertEquals("Expected Integer at position " + i, - Constants.SQLITE_INTEGER, st.column_type(i)); - } - - assertEquals(Constants.SQLITE_NULL, st.column_type(28)); - assertEquals(Constants.SQLITE_NULL, st.column_type(29)); - - // Failing tests - assertTrue("INTEGER".equalsIgnoreCase(st.column_decltype(12))); - assertEquals(Constants.SQLITE_INTEGER, st.column_type(12)); - - assertTrue("FLOAT".equalsIgnoreCase(st.column_decltype(11))); - assertEquals(Constants.SQLITE_FLOAT, st.column_type(11)); // FLOAT -> - // got INTEGER - assertTrue("BLOB".equalsIgnoreCase(st.column_decltype(19))); - assertEquals(Constants.SQLITE_BLOB, st.column_type(19)); // Blob got - // INTEGER - - } - - /** - * Wrong value is returned in case of a prepared statement to which a '*' bound - */ - public void testColumn_count() throws Exception { - String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1; - st = db.prepare(selectStmt); - - assertEquals(3, st.column_count()); - - st.step(); - int columnCount = st.column_count(); - assertNotNull(columnCount); - assertEquals( 3, columnCount); - - // actual prepared statement - selectStmt = "select ? from "+DatabaseCreator.SIMPLE_TABLE1; - st = db.prepare(selectStmt); - - assertEquals(3, st.column_count()); - - st.bind(1, "*"); - st.step(); - columnCount = st.column_count(); - assertNotNull(columnCount); - assertEquals( 3, columnCount); - } - - public void testColumn() throws Exception { - Object columnObject; - int intColumn; - String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1; - db.get_table(selectStmt); - st = db.prepare(selectStmt); - st.step(); - columnObject = st.column(1); - intColumn = st.column_int(1); - assertNotNull(intColumn); - assertTrue("Integer".equalsIgnoreCase(st.column_decltype(1))); - int stSpeed = Integer.parseInt(columnObject.toString()); - assertNotNull(stSpeed); - assertEquals( intColumn, stSpeed); - - try { - assertNotNull(columnObject); - ((Integer) columnObject).intValue(); - fail("Cast to Integer should fail"); - } catch (ClassCastException expected) { - } - - try { - st.column(4); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - assertEquals("column out of bounds", expected.getMessage()); - } - - try { - st.column(-1); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - assertEquals("column out of bounds", expected.getMessage()); - } - } - - public void testColumn_table_name() { - try { - st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1); - st.column_table_name(1); - fail("Function is now supported."); - } catch (SQLite.Exception expected) { - assertEquals("unsupported", expected.getMessage()); - } - } - - public void testColumn_database_name() { - try { - st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (:one,:two,:three)"); - st.column_database_name(1); - fail("Function is now supported."); - } catch (SQLite.Exception expected) { - assertEquals("unsupported", expected.getMessage()); - } - } - - public void testColumn_decltype() throws Exception { - db.exec(CREATE_ALL_TYPES, null); - db.exec(INSERT_ALL_TYPES, null); - st = db.prepare("select * from " + ALL_TYPES_TABLE); - st.step(); - - // Exception test - try { - st.column_decltype(100); - fail(); - } catch (SQLite.Exception expected) { - } - - assertTrue(st.column_decltype(0), "BOOLEAN".equalsIgnoreCase(st - .column_decltype(0))); - assertTrue(st.column_decltype(1), "INT".equalsIgnoreCase(st - .column_decltype(1))); - assertTrue(st.column_decltype(2), "LONG".equalsIgnoreCase(st - .column_decltype(2))); - assertTrue(st.column_decltype(3), "BIGINT".equalsIgnoreCase(st - .column_decltype(3))); - assertTrue(st.column_decltype(4), "TINYINT".equalsIgnoreCase(st - .column_decltype(4))); - assertTrue(st.column_decltype(5), "SMALLINT".equalsIgnoreCase(st - .column_decltype(5))); - assertTrue(st.column_decltype(6), "MEDIUMINT".equalsIgnoreCase(st - .column_decltype(6))); - assertTrue(st.column_decltype(7), "INTEGER".equalsIgnoreCase(st - .column_decltype(7))); - assertTrue(st.column_decltype(8), "REAL".equalsIgnoreCase(st - .column_decltype(8))); - assertTrue(st.column_decltype(9), "DOUBLE".equalsIgnoreCase(st - .column_decltype(9))); - assertTrue(st.column_decltype(10), "FLOAT".equalsIgnoreCase(st - .column_decltype(10))); - assertTrue(st.column_decltype(11), "DECIMAL".equalsIgnoreCase(st - .column_decltype(11))); - assertTrue(st.column_decltype(12), "NUMERIC".equalsIgnoreCase(st - .column_decltype(12))); - assertTrue(st.column_decltype(13), "CHAR(20)".equalsIgnoreCase(st - .column_decltype(13))); - - assertTrue(st.column_decltype(19), "BLOB".equalsIgnoreCase(st - .column_decltype(19))); - - assertTrue(st.column_decltype(23), "TEXT".equalsIgnoreCase(st - .column_decltype(23))); - assertTrue(st.column_decltype(28), "URL".equalsIgnoreCase(st - .column_decltype(28))); - assertTrue(st.column_decltype(29), "URL".equalsIgnoreCase(st - .column_decltype(29))); - } - - public void testColumn_origin_name() { - try { - st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1); - st.column_origin_name(1); - fail("Function is now supported."); - } catch (SQLite.Exception expected) { - assertEquals("unsupported", expected.getMessage()); - } - } -} diff --git a/luni/src/test/java/libcore/sqlite/QueryTimeoutTest.java b/luni/src/test/java/libcore/sqlite/QueryTimeoutTest.java deleted file mode 100644 index 8febfff..0000000 --- a/luni/src/test/java/libcore/sqlite/QueryTimeoutTest.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright (C) 2007 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.sqlite; - -import SQLite.Database; -import SQLite.Function; -import SQLite.FunctionContext; -import SQLite.JDBC2z.JDBCConnection; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import junit.framework.TestCase; -import tests.support.Support_SQL; - - -/** - * Test that statements honor their timeout. - */ -public final class QueryTimeoutTest extends TestCase { - - private static final String EXEC_QUERY - = "insert into t_copy select a from t_orig where DELAY(2,1)=1"; - - private static final String FETCH_QUERY = "select a from t_orig where DELAY(2,1)=1"; - - private Connection connection; - - @Override public void setUp() throws Exception { - Support_SQL.loadDriver(); - connection = Support_SQL.getConnection(); - - exec("drop table if exists t_orig;"); - exec("drop table if exists t_copy;"); - exec("create table t_orig (a int)"); - exec("create table t_copy (a int)"); - - for (int i = 0; i < 7; i++) { - exec("insert into t_orig values (" + i + ");"); - } - - Database database = ((JDBCConnection) connection).getSQLiteDatabase(); - database.create_function("DELAY", 2, new Function() { - @Override public void function(FunctionContext functionContext, String[] args) { - try { - int seconds = Integer.parseInt(args[0]); - Thread.sleep(seconds * 1000); - } catch (InterruptedException ignored) { - } - functionContext.set_result(Integer.parseInt(args[1])); - } - @Override public void last_step(FunctionContext functionContext) { - } - @Override public void step(FunctionContext functionContext, String[] args) { - } - }); - - connection.setAutoCommit(true); - } - - @Override public void tearDown() throws Exception { - connection.close(); - } - - private void exec(String queryString) throws Exception { - System.out.println("Executing " + queryString); - Statement statement = null; - try { - statement = connection.createStatement(); - statement.execute(queryString); - } finally { - if (statement != null) { - statement.close(); - } - } - } - - public void testPreparedStatementFetch() throws Exception { - PreparedStatement statement = connection.prepareStatement(FETCH_QUERY); - statement.setQueryTimeout(1); - ResultSet resultSet = null; - try { - resultSet = statement.executeQuery(); - while (resultSet.next()) { - } - fail(); - } catch (SQLException expected) { - } finally { - statement.close(); - if (resultSet != null) { - resultSet.close(); - } - } - } - - public void testPreparedStatementUpdate() throws Exception { - PreparedStatement statement = connection.prepareStatement(EXEC_QUERY); - try { - statement.setQueryTimeout(1); - statement.execute(); - fail(); - } catch (SQLException expected) { - } finally { - statement.close(); - } - } - - public void testInvalidTimeout() throws Exception { - connection.setAutoCommit(true); - PreparedStatement statement = connection.prepareStatement("select 'hello'"); - - try { - statement.setQueryTimeout(-1); - fail(); - } catch (SQLException expected) { - } - - ResultSet resultSet = statement.executeQuery(); - resultSet.close(); - statement.close(); - } - - public void testExecuteUpdate() throws Exception { - Statement statement = connection.createStatement(); - try { - statement.setQueryTimeout(1); - statement.executeUpdate(EXEC_QUERY); - fail(); - } catch (SQLException expected) { - } finally { - statement.close(); - } - } - - public void testTimeoutAndStatementReuse() throws Exception { - Statement statement = connection.createStatement(); - statement.setQueryTimeout(1); - for (int i = 0; i < 3; i++) { - try { - ResultSet resultSet = statement.executeQuery(FETCH_QUERY); - while (resultSet.next()) { - } - fail(); - } catch (SQLException expected) { - } - } - statement.close(); - } -} diff --git a/luni/src/test/java/libcore/util/ZoneInfoDBTest.java b/luni/src/test/java/libcore/util/ZoneInfoDBTest.java index 28ae416..9875647 100644 --- a/luni/src/test/java/libcore/util/ZoneInfoDBTest.java +++ b/luni/src/test/java/libcore/util/ZoneInfoDBTest.java @@ -22,25 +22,27 @@ import java.io.RandomAccessFile; import java.util.TimeZone; public class ZoneInfoDBTest extends junit.framework.TestCase { - private static final String CURRENT_VERSION = ZoneInfoDB.getInstance().getVersion(); - // Any new file in /data... - private static final String TZDATA_IN_DATA = System.getenv("ANDROID_DATA") + "/misc/zoneinfo/tzdata"; - // ...overrides any existing file in /system. - private static final String TZDATA_IN_ROOT = System.getenv("ANDROID_ROOT") + "/usr/share/zoneinfo/tzdata"; + // The base tzdata file, always present on a device. + private static final String TZDATA_IN_ROOT = + System.getenv("ANDROID_ROOT") + "/usr/share/zoneinfo/tzdata"; // An empty override file should fall back to the default file. public void testEmptyOverrideFile() throws Exception { - ZoneInfoDB.TzData data = new ZoneInfoDB.TzData(makeEmptyFile(), TZDATA_IN_DATA, TZDATA_IN_ROOT); - assertEquals(CURRENT_VERSION, data.getVersion()); - assertEquals(TimeZone.getAvailableIDs().length, data.getAvailableIDs().length); + ZoneInfoDB.TzData data = new ZoneInfoDB.TzData(TZDATA_IN_ROOT); + ZoneInfoDB.TzData dataWithEmptyOverride = + new ZoneInfoDB.TzData(makeEmptyFile(), TZDATA_IN_ROOT); + assertEquals(data.getVersion(), dataWithEmptyOverride.getVersion()); + assertEquals(data.getAvailableIDs().length, dataWithEmptyOverride.getAvailableIDs().length); } // A corrupt override file should fall back to the default file. public void testCorruptOverrideFile() throws Exception { - ZoneInfoDB.TzData data = new ZoneInfoDB.TzData(makeCorruptFile(), TZDATA_IN_DATA, TZDATA_IN_ROOT); - assertEquals(CURRENT_VERSION, data.getVersion()); - assertEquals(TimeZone.getAvailableIDs().length, data.getAvailableIDs().length); + ZoneInfoDB.TzData data = new ZoneInfoDB.TzData(TZDATA_IN_ROOT); + ZoneInfoDB.TzData dataWithCorruptOverride = + new ZoneInfoDB.TzData(makeCorruptFile(), TZDATA_IN_ROOT); + assertEquals(data.getVersion(), dataWithCorruptOverride.getVersion()); + assertEquals(data.getAvailableIDs().length, dataWithCorruptOverride.getAvailableIDs().length); } // Given no tzdata files we can use, we should fall back to built-in "GMT". @@ -53,7 +55,6 @@ public class ZoneInfoDBTest extends junit.framework.TestCase { // Given a valid override file, we should find ourselves using that. public void testGoodOverrideFile() throws Exception { - // We copy /system/usr/share/zoneinfo/tzdata because we know that always exists. RandomAccessFile in = new RandomAccessFile(TZDATA_IN_ROOT, "r"); byte[] content = new byte[(int) in.length()]; in.readFully(content); @@ -65,16 +66,40 @@ public class ZoneInfoDBTest extends junit.framework.TestCase { content[10] = 'z'; in.close(); + ZoneInfoDB.TzData data = new ZoneInfoDB.TzData(TZDATA_IN_ROOT); String goodFile = makeTemporaryFile(content); try { - ZoneInfoDB.TzData data = new ZoneInfoDB.TzData(goodFile, TZDATA_IN_DATA, TZDATA_IN_ROOT); - assertEquals("9999z", data.getVersion()); - assertEquals(TimeZone.getAvailableIDs().length, data.getAvailableIDs().length); + ZoneInfoDB.TzData dataWithOverride = new ZoneInfoDB.TzData(goodFile, TZDATA_IN_ROOT); + assertEquals("9999z", dataWithOverride.getVersion()); + assertEquals(data.getAvailableIDs().length, dataWithOverride.getAvailableIDs().length); } finally { new File(goodFile).delete(); } } + // Confirms any caching that exists correctly handles TimeZone mutability. + public void testMakeTimeZone_timeZoneMutability() throws Exception { + ZoneInfoDB.TzData data = new ZoneInfoDB.TzData(TZDATA_IN_ROOT); + String tzId = "Europe/London"; + ZoneInfo first = data.makeTimeZone(tzId); + ZoneInfo second = data.makeTimeZone(tzId); + assertNotSame(first, second); + + assertTrue(first.hasSameRules(second)); + + first.setID("Not Europe/London"); + + assertFalse(first.getID().equals(second.getID())); + + first.setRawOffset(3600); + assertFalse(first.getRawOffset() == second.getRawOffset()); + } + + public void testMakeTimeZone_notFound() throws Exception { + ZoneInfoDB.TzData data = new ZoneInfoDB.TzData(TZDATA_IN_ROOT); + assertNull(data.makeTimeZone("THIS_TZ_DOES_NOT_EXIST")); + } + private static String makeCorruptFile() throws Exception { return makeTemporaryFile("invalid content".getBytes()); } diff --git a/luni/src/test/java/libcore/xml/XmlPullParserFactoryTest.java b/luni/src/test/java/libcore/xml/XmlPullParserFactoryTest.java new file mode 100644 index 0000000..7194414 --- /dev/null +++ b/luni/src/test/java/libcore/xml/XmlPullParserFactoryTest.java @@ -0,0 +1,374 @@ +/* + * Copyright (C) 2013 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.xml; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.io.Writer; +import junit.framework.TestCase; +import org.kxml2.io.KXmlParser; +import org.kxml2.io.KXmlSerializer; +import org.xmlpull.v1.XmlPullParser; +import org.xmlpull.v1.XmlPullParserException; +import org.xmlpull.v1.XmlPullParserFactory; +import org.xmlpull.v1.XmlSerializer; + +public class XmlPullParserFactoryTest extends TestCase { + + public void testDefaultNewInstance() throws Exception { + XmlPullParserFactory factory = XmlPullParserFactory.newInstance(null, null); + XmlPullParser parser = factory.newPullParser(); + XmlSerializer serializer = factory.newSerializer(); + + assertNotNull(parser); + assertNotNull(serializer); + assertTrue(parser instanceof KXmlParser); + assertTrue(serializer instanceof KXmlSerializer); + } + + /** + * Tests that trying to instantiate a parser with an empty list of + * parsers and serializers fails. + */ + public void testOverriding_emptyClassList() { + TestXmlPullParserFactory tf = new TestXmlPullParserFactory(null, null); + + try { + tf.newPullParser(); + fail(); + } catch (XmlPullParserException expected) { + } + + try { + tf.newPullParser(); + fail(); + } catch (XmlPullParserException expected) { + } + } + + public void testOverriding_customClassList() throws Exception { + TestXmlPullParserFactory tf = new TestXmlPullParserFactory( + new String[] { "libcore.xml.XmlPullParserFactoryTest$XmlPullParserStub" }, + new String[] { "libcore.xml.XmlPullParserFactoryTest$XmlSerializerStub" }); + + assertTrue(tf.newPullParser() instanceof XmlPullParserStub); + assertTrue(tf.newSerializer() instanceof XmlSerializerStub); + + // Also check that we ignore instantiation errors as long as + // at least one parser / serializer is instantiable. + tf = new TestXmlPullParserFactory( + new String[] { + "libcore.xml.XmlPullParserFactoryTest$InaccessibleXmlParser", + "libcore.xml.XmlPullParserFactoryTest$XmlPullParserStub" }, + new String[] { + "libcore.xml.XmlPullParserFactoryTest$InaccessibleXmlSerializer", + "libcore.xml.XmlPullParserFactoryTest$XmlSerializerStub" }); + + assertTrue(tf.newPullParser() instanceof XmlPullParserStub); + assertTrue(tf.newSerializer() instanceof XmlSerializerStub); + } + + // https://b/12956724 + public void testSetFeature_setsFeatureOnlyIfTrue() throws Exception { + TestXmlPullParserFactory tf = new TestXmlPullParserFactory( + new String[] { "libcore.xml.XmlPullParserFactoryTest$XmlParserThatHatesAllFeatures" }, null); + + tf.setFeature("foo", false); + tf.newPullParser(); + } + + + /** + * A class that makes use of inherited XmlPullParserFactory fields to check they are + * supported. + */ + static final class TestXmlPullParserFactory extends XmlPullParserFactory { + TestXmlPullParserFactory(String[] parserClassList, String[] serializerClassList) { + super(); + parserClasses.remove(0); + serializerClasses.remove(0); + + try { + if (parserClassList != null) { + for (String parserClass : parserClassList) { + parserClasses.add(Class.forName(parserClass)); + } + } + + if (serializerClassList != null) { + for (String serializerClass : serializerClassList) { + serializerClasses.add(Class.forName(serializerClass)); + } + } + } catch (ClassNotFoundException ignored) { + throw new AssertionError(ignored); + } + } + } + + public static final class XmlParserThatHatesAllFeatures extends XmlPullParserStub { + @Override + public void setFeature(String name, boolean state) { + fail(); + } + } + + static final class InaccessibleXmlSerializer extends XmlSerializerStub { + } + + static final class InaccessibleXmlParser extends XmlPullParserStub { + } + + public static class XmlSerializerStub implements XmlSerializer { + + public void setFeature(String name, boolean state) throws IllegalArgumentException, + IllegalStateException { + } + + public boolean getFeature(String name) { + return false; + } + + public void setProperty(String name, Object value) { + } + + public Object getProperty(String name) { + return null; + } + + public void setOutput(OutputStream os, String encoding) throws IOException { + } + + public void setOutput(Writer writer) throws IOException { + } + + public void startDocument(String encoding, Boolean standalone) throws IOException { + } + + public void endDocument() throws IOException { + } + + public void setPrefix(String prefix, String namespace) throws IOException { + } + + public String getPrefix(String namespace, boolean generatePrefix) throws IllegalArgumentException { + return null; + } + + public int getDepth() { + return 0; + } + + public String getNamespace() { + return null; + } + + public String getName() { + return null; + } + + public XmlSerializer startTag(String namespace, String name) throws IOException { + return null; + } + + public XmlSerializer attribute(String namespace, String name, String value) throws IOException { + return null; + } + + public XmlSerializer endTag(String namespace, String name) throws IOException { + return null; + } + + public XmlSerializer text(String text) throws IOException { + return null; + } + + public XmlSerializer text(char[] buf, int start, int len) throws IOException { + return null; + } + + public void cdsect(String text) throws IOException { + } + + public void entityRef(String text) throws IOException { + } + + public void processingInstruction(String text) throws IOException { + } + + public void comment(String text) throws IOException { + } + + public void docdecl(String text) throws IOException { + } + + public void ignorableWhitespace(String text) throws IOException { + } + + public void flush() throws IOException { + } + } + + public static class XmlPullParserStub implements XmlPullParser { + public void setFeature(String name, boolean state) throws XmlPullParserException { + } + + public boolean getFeature(String name) { + return false; + } + + public void setProperty(String name, Object value) throws XmlPullParserException { + } + + public Object getProperty(String name) { + return null; + } + + public void setInput(Reader in) throws XmlPullParserException { + } + + public void setInput(InputStream inputStream, String inputEncoding) + throws XmlPullParserException { + } + + public String getInputEncoding() { + return null; + } + + public void defineEntityReplacementText(String entityName, String replacementText) + throws XmlPullParserException { + } + + public int getNamespaceCount(int depth) throws XmlPullParserException { + return 0; + } + + public String getNamespacePrefix(int pos) throws XmlPullParserException { + return null; + } + + public String getNamespaceUri(int pos) throws XmlPullParserException { + return null; + } + + public String getNamespace(String prefix) { + return null; + } + + public int getDepth() { + return 0; + } + + public String getPositionDescription() { + return null; + } + + public int getLineNumber() { + return 0; + } + + public int getColumnNumber() { + return 0; + } + + public boolean isWhitespace() throws XmlPullParserException { + return false; + } + + public String getText() { + return null; + } + + public char[] getTextCharacters(int[] holderForStartAndLength) { + return null; + } + + public String getNamespace() { + return null; + } + + public String getName() { + return null; + } + + public String getPrefix() { + return null; + } + + public boolean isEmptyElementTag() throws XmlPullParserException { + return false; + } + + public int getAttributeCount() { + return 0; + } + + public String getAttributeNamespace(int index) { + return null; + } + + public String getAttributeName(int index) { + return null; + } + + public String getAttributePrefix(int index) { + return null; + } + + public String getAttributeType(int index) { + return null; + } + + public boolean isAttributeDefault(int index) { + return false; + } + + public String getAttributeValue(int index) { + return null; + } + + public String getAttributeValue(String namespace, String name) { + return null; + } + + public int getEventType() throws XmlPullParserException { + return 0; + } + + public int next() throws XmlPullParserException, IOException { + return 0; + } + + public int nextToken() throws XmlPullParserException, IOException { + return 0; + } + + public void require(int type, String namespace, String name) + throws XmlPullParserException, IOException { + } + + public String nextText() throws XmlPullParserException, IOException { + return null; + } + + public int nextTag() throws XmlPullParserException, IOException { + return 0; + } + } +} diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarFileTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarFileTest.java deleted file mode 100644 index afdce5d..0000000 --- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarFileTest.java +++ /dev/null @@ -1,1001 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.harmony.archive.tests.java.util.jar; - - -import junit.framework.TestCase; - -import tests.support.Support_PlatformFile; -import tests.support.resource.Support_Resources; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.security.Permission; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.Vector; -import java.util.jar.Attributes; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.jar.JarOutputStream; -import java.util.jar.Manifest; -import java.util.zip.ZipEntry; -import java.util.zip.ZipException; -import java.util.zip.ZipFile; - - -public class JarFileTest extends TestCase { - - // BEGIN android-added - public byte[] getAllBytesFromStream(InputStream is) throws IOException { - ByteArrayOutputStream bs = new ByteArrayOutputStream(); - byte[] buf = new byte[666]; - int iRead; - int off; - while (is.available() > 0) { - iRead = is.read(buf, 0, buf.length); - if (iRead > 0) bs.write(buf, 0, iRead); - } - return bs.toByteArray(); - } - - // END android-added - - private final String jarName = "hyts_patch.jar"; // a 'normal' jar file - - private final String jarName2 = "hyts_patch2.jar"; - - private final String jarName3 = "hyts_manifest1.jar"; - - private final String jarName4 = "hyts_signed.jar"; - - private final String jarName5 = "hyts_signed_inc.jar"; - - private final String jarName6 = "hyts_signed_sha256withrsa.jar"; - - private final String jarName7 = "hyts_signed_sha256digest_sha256withrsa.jar"; - - private final String jarName8 = "hyts_signed_sha512digest_sha512withecdsa.jar"; - - private final String authAttrsJar = "hyts_signed_authAttrs.jar"; - - private final String entryName = "foo/bar/A.class"; - - private final String entryName3 = "coucou/FileAccess.class"; - - private final String integrateJar = "Integrate.jar"; - - private final String integrateJarEntry = "Test.class"; - - private final String emptyEntryJar = "EmptyEntries_signed.jar"; - - private final String emptyEntry1 = "subfolder/internalSubset01.js"; - - private final String emptyEntry2 = "svgtest.js"; - - private final String emptyEntry3 = "svgunit.js"; - - private static final String VALID_CHAIN_JAR = "hyts_signed_validChain.jar"; - - private static final String INVALID_CHAIN_JAR = "hyts_signed_invalidChain.jar"; - - private File resources; - - // custom security manager - SecurityManager sm = new SecurityManager() { - final String forbidenPermissionName = "user.dir"; - - public void checkPermission(Permission perm) { - if (perm.getName().equals(forbidenPermissionName)) { - throw new SecurityException(); - } - } - }; - - @Override - protected void setUp() { - resources = Support_Resources.createTempFolder(); - } - - /** - * java.util.jar.JarFile#JarFile(java.io.File) - */ - public void test_ConstructorLjava_io_File() { - try { - JarFile jarFile = new JarFile(new File("Wrong.file")); - fail("Should throw IOException"); - } catch (IOException e) { - // expected - } - - try { - Support_Resources.copyFile(resources, null, jarName); - JarFile jarFile = new JarFile(new File(resources, jarName)); - } catch (IOException e) { - fail("Should not throw IOException"); - } - } - - /** - * java.util.jar.JarFile#JarFile(java.lang.String) - */ - public void test_ConstructorLjava_lang_String() { - try { - JarFile jarFile = new JarFile("Wrong.file"); - fail("Should throw IOException"); - } catch (IOException e) { - // expected - } - - try { - Support_Resources.copyFile(resources, null, jarName); - String fileName = (new File(resources, jarName)).getCanonicalPath(); - JarFile jarFile = new JarFile(fileName); - } catch (IOException e) { - fail("Should not throw IOException"); - } - } - - /** - * java.util.jar.JarFile#JarFile(java.lang.String, boolean) - */ - public void test_ConstructorLjava_lang_StringZ() { - try { - JarFile jarFile = new JarFile("Wrong.file", false); - fail("Should throw IOException"); - } catch (IOException e) { - // expected - } - - try { - Support_Resources.copyFile(resources, null, jarName); - String fileName = (new File(resources, jarName)).getCanonicalPath(); - JarFile jarFile = new JarFile(fileName, true); - } catch (IOException e) { - fail("Should not throw IOException"); - } - } - - /** - * java.util.jar.JarFile#JarFile(java.io.File, boolean) - */ - public void test_ConstructorLjava_io_FileZ() { - try { - JarFile jarFile = new JarFile(new File("Wrong.file"), true); - fail("Should throw IOException"); - } catch (IOException e) { - // expected - } - - try { - Support_Resources.copyFile(resources, null, jarName); - JarFile jarFile = new JarFile(new File(resources, jarName), false); - } catch (IOException e) { - fail("Should not throw IOException"); - } - } - - /** - * java.util.jar.JarFile#JarFile(java.io.File, boolean, int) - */ - public void test_ConstructorLjava_io_FileZI() { - try { - JarFile jarFile = new JarFile(new File("Wrong.file"), true, - ZipFile.OPEN_READ); - fail("Should throw IOException"); - } catch (IOException e) { - // expected - } - - try { - Support_Resources.copyFile(resources, null, jarName); - JarFile jarFile = new JarFile(new File(resources, jarName), false, - ZipFile.OPEN_READ); - } catch (IOException e) { - fail("Should not throw IOException"); - } - - try { - Support_Resources.copyFile(resources, null, jarName); - JarFile jarFile = new JarFile(new File(resources, jarName), false, - ZipFile.OPEN_READ | ZipFile.OPEN_DELETE + 33); - fail("Should throw IllegalArgumentException"); - } catch (IOException e) { - fail("Should not throw IOException"); - } catch (IllegalArgumentException e) { - // expected - } - } - - /** - * Constructs JarFile object. - * - * java.util.jar.JarFile#JarFile(java.io.File) - * java.util.jar.JarFile#JarFile(java.lang.String) - */ - public void testConstructor_file() throws IOException { - File f = new File(resources, jarName); - Support_Resources.copyFile(resources, null, jarName); - assertTrue(new JarFile(f).getEntry(entryName).getName().equals( - entryName)); - assertTrue(new JarFile(f.getPath()).getEntry(entryName).getName() - .equals(entryName)); - } - - /** - * java.util.jar.JarFile#entries() - */ - public void test_entries() throws Exception { - /* - * Note only (and all of) the following should be contained in the file - * META-INF/ META-INF/MANIFEST.MF foo/ foo/bar/ foo/bar/A.class Blah.txt - */ - Support_Resources.copyFile(resources, null, jarName); - JarFile jarFile = new JarFile(new File(resources, jarName)); - Enumeration<JarEntry> e = jarFile.entries(); - int i; - for (i = 0; e.hasMoreElements(); i++) { - e.nextElement(); - } - assertEquals(jarFile.size(), i); - jarFile.close(); - assertEquals(6, i); - } - - public void test_entries2() throws Exception { - Support_Resources.copyFile(resources, null, jarName); - JarFile jarFile = new JarFile(new File(resources, jarName)); - Enumeration<JarEntry> enumeration = jarFile.entries(); - jarFile.close(); - try { - enumeration.hasMoreElements(); - fail("hasMoreElements() did not detect a closed jar file"); - } catch (IllegalStateException e) { - } - Support_Resources.copyFile(resources, null, jarName); - jarFile = new JarFile(new File(resources, jarName)); - enumeration = jarFile.entries(); - jarFile.close(); - try { - enumeration.nextElement(); - fail("nextElement() did not detect closed jar file"); - } catch (IllegalStateException e) { - } - } - - /** - * @throws IOException - * java.util.jar.JarFile#getJarEntry(java.lang.String) - */ - public void test_getEntryLjava_lang_String() throws IOException { - try { - Support_Resources.copyFile(resources, null, jarName); - JarFile jarFile = new JarFile(new File(resources, jarName)); - assertEquals("Error in returned entry", 311, jarFile.getEntry( - entryName).getSize()); - jarFile.close(); - } catch (Exception e) { - fail("Exception during test: " + e.toString()); - } - - Support_Resources.copyFile(resources, null, jarName); - JarFile jarFile = new JarFile(new File(resources, jarName)); - Enumeration<JarEntry> enumeration = jarFile.entries(); - assertTrue(enumeration.hasMoreElements()); - while (enumeration.hasMoreElements()) { - JarEntry je = enumeration.nextElement(); - jarFile.getEntry(je.getName()); - } - - enumeration = jarFile.entries(); - assertTrue(enumeration.hasMoreElements()); - JarEntry je = enumeration.nextElement(); - try { - jarFile.close(); - jarFile.getEntry(je.getName()); - // fail("IllegalStateException expected."); - } catch (IllegalStateException ee) { // Per documentation exception - // may be thrown. - // expected - } - } - - /** - * @throws IOException - * java.util.jar.JarFile#getJarEntry(java.lang.String) - */ - public void test_getJarEntryLjava_lang_String() throws IOException { - try { - Support_Resources.copyFile(resources, null, jarName); - JarFile jarFile = new JarFile(new File(resources, jarName)); - assertEquals("Error in returned entry", 311, jarFile.getJarEntry( - entryName).getSize()); - jarFile.close(); - } catch (Exception e) { - fail("Exception during test: " + e.toString()); - } - - Support_Resources.copyFile(resources, null, jarName); - JarFile jarFile = new JarFile(new File(resources, jarName)); - Enumeration<JarEntry> enumeration = jarFile.entries(); - assertTrue(enumeration.hasMoreElements()); - while (enumeration.hasMoreElements()) { - JarEntry je = enumeration.nextElement(); - jarFile.getJarEntry(je.getName()); - } - - enumeration = jarFile.entries(); - assertTrue(enumeration.hasMoreElements()); - JarEntry je = enumeration.nextElement(); - try { - jarFile.close(); - jarFile.getJarEntry(je.getName()); - // fail("IllegalStateException expected."); - } catch (IllegalStateException ee) { // Per documentation exception - // may be thrown. - // expected - } - } - - - /** - * java.util.jar.JarFile#getJarEntry(java.lang.String) - */ - public void testGetJarEntry() throws Exception { - Support_Resources.copyFile(resources, null, jarName); - JarFile jarFile = new JarFile(new File(resources, jarName)); - assertEquals("Error in returned entry", 311, jarFile.getEntry( - entryName).getSize()); - jarFile.close(); - - // tests for signed jars - // test all signed jars in the /Testres/Internal/SignedJars directory - String jarDirUrl = Support_Resources - .getResourceURL("/../internalres/signedjars"); - Vector<String> signedJars = new Vector<String>(); - try { - InputStream is = new URL(jarDirUrl + "/jarlist.txt").openStream(); - while (is.available() > 0) { - StringBuilder linebuff = new StringBuilder(80); // Typical line - // length - done: while (true) { - int nextByte = is.read(); - switch (nextByte) { - case -1: - break done; - case (byte) '\r': - if (linebuff.length() == 0) { - // ignore - } - break done; - case (byte) '\n': - if (linebuff.length() == 0) { - // ignore - } - break done; - default: - linebuff.append((char) nextByte); - } - } - if (linebuff.length() == 0) { - break; - } - String line = linebuff.toString(); - signedJars.add(line); - } - is.close(); - } catch (IOException e) { - // no list of jars found - } - - for (int i = 0; i < signedJars.size(); i++) { - String jarName = signedJars.get(i); - try { - File file = Support_Resources.getExternalLocalFile(jarDirUrl - + "/" + jarName); - jarFile = new JarFile(file, true); - boolean foundCerts = false; - Enumeration<JarEntry> e = jarFile.entries(); - while (e.hasMoreElements()) { - JarEntry entry = e.nextElement(); - InputStream is = jarFile.getInputStream(entry); - is.skip(100000); - is.close(); - Certificate[] certs = entry.getCertificates(); - if (certs != null && certs.length > 0) { - foundCerts = true; - break; - } - } - assertTrue( - "No certificates found during signed jar test for jar \"" - + jarName + "\"", foundCerts); - } catch (IOException e) { - fail("Exception during signed jar test for jar \"" + jarName - + "\": " + e.toString()); - } - } - } - - /** - * java.util.jar.JarFile#getManifest() - */ - public void test_getManifest() { - // Test for method java.util.jar.Manifest - // java.util.jar.JarFile.getManifest() - try { - Support_Resources.copyFile(resources, null, jarName); - JarFile jarFile = new JarFile(new File(resources, jarName)); - assertNotNull("Error--Manifest not returned", jarFile.getManifest()); - jarFile.close(); - } catch (Exception e) { - fail("Exception during 1st test: " + e.toString()); - } - try { - Support_Resources.copyFile(resources, null, jarName2); - JarFile jarFile = new JarFile(new File(resources, jarName2)); - assertNull("Error--should have returned null", jarFile - .getManifest()); - jarFile.close(); - } catch (Exception e) { - fail("Exception during 2nd test: " + e.toString()); - } - - try { - // jarName3 was created using the following test - Support_Resources.copyFile(resources, null, jarName3); - JarFile jarFile = new JarFile(new File(resources, jarName3)); - assertNotNull("Should find manifest without verifying", jarFile - .getManifest()); - jarFile.close(); - } catch (Exception e) { - fail("Exception during 3rd test: " + e.toString()); - } - - try { - // this is used to create jarName3 used in the previous test - Manifest manifest = new Manifest(); - Attributes attributes = manifest.getMainAttributes(); - attributes.put(new Attributes.Name("Manifest-Version"), "1.0"); - ByteArrayOutputStream manOut = new ByteArrayOutputStream(); - manifest.write(manOut); - byte[] manBytes = manOut.toByteArray(); - File file = File.createTempFile( - Support_PlatformFile.getNewPlatformFile("hyts_manifest1", - ""), ".jar"); - JarOutputStream jarOut = new JarOutputStream(new FileOutputStream( - file.getAbsolutePath())); - ZipEntry entry = new ZipEntry("META-INF/"); - entry.setSize(0); - jarOut.putNextEntry(entry); - entry = new ZipEntry(JarFile.MANIFEST_NAME); - entry.setSize(manBytes.length); - jarOut.putNextEntry(entry); - jarOut.write(manBytes); - entry = new ZipEntry("myfile"); - entry.setSize(1); - jarOut.putNextEntry(entry); - jarOut.write(65); - jarOut.close(); - JarFile jar = new JarFile(file.getAbsolutePath(), false); - assertNotNull("Should find manifest without verifying", jar - .getManifest()); - jar.close(); - file.delete(); - } catch (IOException e) { - fail("IOException 3"); - } - try { - Support_Resources.copyFile(resources, null, jarName2); - JarFile jF = new JarFile(new File(resources, jarName2)); - jF.close(); - jF.getManifest(); - fail("FAILED: expected IllegalStateException"); - } catch (IllegalStateException ise) { - // expected; - } catch (Exception e) { - fail("Exception during 4th test: " + e.toString()); - } - - Support_Resources.copyFile(resources, null, "Broken_manifest.jar"); - JarFile jf; - try { - jf = new JarFile(new File(resources, "Broken_manifest.jar")); - jf.getManifest(); - fail("IOException expected."); - } catch (IOException e) { - // expected. - } - } - - /** - * java.util.jar.JarFile#getInputStream(java.util.zip.ZipEntry) - */ - // This test doesn't pass on RI. If entry size is set up incorrectly, - // SecurityException is thrown. But SecurityException is thrown on RI only - // if jar file is signed incorrectly. - public void test_getInputStreamLjava_util_jar_JarEntry_subtest0() throws Exception { - File signedFile = null; - try { - Support_Resources.copyFile(resources, null, jarName4); - signedFile = new File(resources, jarName4); - } catch (Exception e) { - fail("Failed to create local file 2: " + e); - } - - try { - JarFile jar = new JarFile(signedFile); - JarEntry entry = new JarEntry(entryName3); - InputStream in = jar.getInputStream(entry); - in.read(); - } catch (Exception e) { - fail("Exception during test 3: " + e); - } - - try { - JarFile jar = new JarFile(signedFile); - JarEntry entry = new JarEntry(entryName3); - InputStream in = jar.getInputStream(entry); - // BEGIN android-added - byte[] dummy = getAllBytesFromStream(in); - // END android-added - assertNull("found certificates", entry.getCertificates()); - } catch (Exception e) { - fail("Exception during test 4: " + e); - } - - try { - JarFile jar = new JarFile(signedFile); - JarEntry entry = new JarEntry(entryName3); - entry.setSize(1076); - InputStream in = jar.getInputStream(entry); - // BEGIN android-added - byte[] dummy = getAllBytesFromStream(in); - // END android-added - fail("SecurityException should be thrown."); - } catch (SecurityException e) { - // expected - } catch (Exception e) { - fail("Exception during test 5: " + e); - } - - try { - Support_Resources.copyFile(resources, null, jarName5); - signedFile = new File(resources, jarName5); - } catch (Exception e) { - fail("Failed to create local file 5: " + e); - } - - try { - JarFile jar = new JarFile(signedFile); - JarEntry entry = new JarEntry(entryName3); - InputStream in = jar.getInputStream(entry); - fail("SecurityException should be thrown."); - } catch (SecurityException e) { - // expected - } catch (Exception e) { - fail("Exception during test 5: " + e); - } - - // SHA1 digest, SHA256withRSA signed JAR - checkSignedJar(jarName6); - - // SHA-256 digest, SHA256withRSA signed JAR - checkSignedJar(jarName7); - - // SHA-512 digest, SHA512withECDSA signed JAR - checkSignedJar(jarName8); - - // JAR with a signature that has PKCS#7 Authenticated Attributes - checkSignedJar(authAttrsJar); - } - - private void checkSignedJar(String jarName) throws Exception { - Support_Resources.copyFile(resources, null, jarName); - - File file = new File(resources, jarName); - - JarFile jarFile = new JarFile(file, true); - - boolean foundCerts = false; - - Enumeration<JarEntry> e = jarFile.entries(); - while (e.hasMoreElements()) { - JarEntry entry = e.nextElement(); - InputStream is = jarFile.getInputStream(entry); - is.skip(100000); - is.close(); - Certificate[] certs = entry.getCertificates(); - if (certs != null && certs.length > 0) { - foundCerts = true; - break; - } - } - - assertTrue( - "No certificates found during signed jar test for jar \"" - + jarName + "\"", foundCerts); - } - - private Certificate[] getSignedJarCerts(String jarName, boolean chainCheck) throws Exception { - Support_Resources.copyFile(resources, null, jarName); - - File file = new File(resources, jarName); - Certificate[] foundCerts = null; - - JarFile jarFile = new JarFile(file, true, ZipFile.OPEN_READ, chainCheck); - try { - - Enumeration<JarEntry> e = jarFile.entries(); - while (e.hasMoreElements()) { - JarEntry entry = e.nextElement(); - InputStream is = jarFile.getInputStream(entry); - // Skip bytes because we have to read the entire file for it to read signatures. - is.skip(entry.getSize()); - is.close(); - Certificate[] certs = entry.getCertificates(); - if (certs != null && certs.length > 0) { - foundCerts = certs; - break; - } - } - } finally { - jarFile.close(); - } - - return foundCerts; - } - - public void testJarFile_Signed_ValidChain_NoCheck() throws Exception { - Certificate[] certs = getSignedJarCerts(VALID_CHAIN_JAR, false); - assertNotNull(certs); - assertEquals(Arrays.deepToString(certs), 3, certs.length); - assertEquals("CN=fake-chain", ((X509Certificate) certs[0]).getSubjectDN().toString()); - assertEquals("CN=intermediate1", ((X509Certificate) certs[1]).getSubjectDN().toString()); - assertEquals("CN=root1", ((X509Certificate) certs[2]).getSubjectDN().toString()); - } - - public void testJarFile_Signed_ValidChain_Check() throws Exception { - Certificate[] certs = getSignedJarCerts(VALID_CHAIN_JAR, true); - assertNotNull(certs); - assertEquals(Arrays.deepToString(certs), 3, certs.length); - assertEquals("CN=fake-chain", ((X509Certificate) certs[0]).getSubjectDN().toString()); - assertEquals("CN=intermediate1", ((X509Certificate) certs[1]).getSubjectDN().toString()); - assertEquals("CN=root1", ((X509Certificate) certs[2]).getSubjectDN().toString()); - } - - public void testJarFile_Signed_InvalidChain_NoCheck() throws Exception { - Certificate[] certs = getSignedJarCerts(INVALID_CHAIN_JAR, false); - assertNotNull(certs); - assertEquals(Arrays.deepToString(certs), 3, certs.length); - assertEquals("CN=fake-chain", ((X509Certificate) certs[0]).getSubjectDN().toString()); - assertEquals("CN=intermediate1", ((X509Certificate) certs[1]).getSubjectDN().toString()); - assertEquals("CN=root1", ((X509Certificate) certs[2]).getSubjectDN().toString()); - } - - public void testJarFile_Signed_InvalidChain_Check() throws Exception { - Certificate[] certs = getSignedJarCerts(INVALID_CHAIN_JAR, true); - assertNotNull(certs); - assertEquals(Arrays.deepToString(certs), 2, certs.length); - assertEquals("CN=fake-chain", ((X509Certificate) certs[0]).getSubjectDN().toString()); - assertEquals("CN=intermediate1", ((X509Certificate) certs[1]).getSubjectDN().toString()); - } - - /* - * The jar created by 1.4 which does not provide a - * algorithm-Digest-Manifest-Main-Attributes entry in .SF file. - */ - public void test_Jar_created_before_java_5() throws IOException { - String modifiedJarName = "Created_by_1_4.jar"; - Support_Resources.copyFile(resources, null, modifiedJarName); - JarFile jarFile = new JarFile(new File(resources, modifiedJarName), - true); - Enumeration<JarEntry> entries = jarFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry zipEntry = entries.nextElement(); - jarFile.getInputStream(zipEntry); - } - } - - /* The jar is intact, then everything is all right. */ - public void test_JarFile_Integrate_Jar() throws IOException { - String modifiedJarName = "Integrate.jar"; - Support_Resources.copyFile(resources, null, modifiedJarName); - JarFile jarFile = new JarFile(new File(resources, modifiedJarName), - true); - Enumeration<JarEntry> entries = jarFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry zipEntry = entries.nextElement(); - jarFile.getInputStream(zipEntry).skip(Long.MAX_VALUE); - } - } - - /** - * The jar is intact, but the entry object is modified. - */ - public void testJarVerificationModifiedEntry() throws IOException { - Support_Resources.copyFile(resources, null, integrateJar); - File f = new File(resources, integrateJar); - - JarFile jarFile = new JarFile(f); - ZipEntry zipEntry = jarFile.getJarEntry(integrateJarEntry); - zipEntry.setSize(zipEntry.getSize() + 1); - jarFile.getInputStream(zipEntry).skip(Long.MAX_VALUE); - - jarFile = new JarFile(f); - zipEntry = jarFile.getJarEntry(integrateJarEntry); - zipEntry.setSize(zipEntry.getSize() - 1); - try { - //jarFile.getInputStream(zipEntry).skip(Long.MAX_VALUE); - jarFile.getInputStream(zipEntry).read(new byte[5000], 0, 5000); - fail("SecurityException expected"); - } catch (SecurityException e) { - // desired - } - } - - /* - * If another entry is inserted into Manifest, no security exception will be - * thrown out. - */ - public void test_JarFile_InsertEntry_in_Manifest_Jar() throws IOException { - String modifiedJarName = "Inserted_Entry_Manifest.jar"; - Support_Resources.copyFile(resources, null, modifiedJarName); - JarFile jarFile = new JarFile(new File(resources, modifiedJarName), - true); - Enumeration<JarEntry> entries = jarFile.entries(); - int count = 0; - while (entries.hasMoreElements()) { - - ZipEntry zipEntry = entries.nextElement(); - jarFile.getInputStream(zipEntry); - count++; - } - assertEquals(5, count); - } - - /* - * If another entry is inserted into Manifest, no security exception will be - * thrown out. - */ - public void test_Inserted_Entry_Manifest_with_DigestCode() - throws IOException { - String modifiedJarName = "Inserted_Entry_Manifest_with_DigestCode.jar"; - Support_Resources.copyFile(resources, null, modifiedJarName); - JarFile jarFile = new JarFile(new File(resources, modifiedJarName), - true); - Enumeration<JarEntry> entries = jarFile.entries(); - int count = 0; - while (entries.hasMoreElements()) { - ZipEntry zipEntry = entries.nextElement(); - jarFile.getInputStream(zipEntry); - count++; - } - assertEquals(5, count); - } - - /* - * The content of Test.class is modified, jarFile.getInputStream will not - * throw security Exception, but it will anytime before the inputStream got - * from getInputStream method has been read to end. - */ - public void test_JarFile_Modified_Class() throws IOException { - String modifiedJarName = "Modified_Class.jar"; - Support_Resources.copyFile(resources, null, modifiedJarName); - JarFile jarFile = new JarFile(new File(resources, modifiedJarName), - true); - Enumeration<JarEntry> entries = jarFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry zipEntry = entries.nextElement(); - jarFile.getInputStream(zipEntry); - } - /* The content of Test.class has been tampered. */ - ZipEntry zipEntry = jarFile.getEntry("Test.class"); - InputStream in = jarFile.getInputStream(zipEntry); - byte[] buffer = new byte[1024]; - try { - while (in.available() > 0) { - in.read(buffer); - } - fail("SecurityException expected"); - } catch (SecurityException e) { - // desired - } - } - - /* - * In the Modified.jar, the main attributes of META-INF/MANIFEST.MF is - * tampered manually. Hence the RI 5.0 JarFile.getInputStream of any - * JarEntry will throw security exception. - */ - public void test_JarFile_Modified_Manifest_MainAttributes() - throws IOException { - String modifiedJarName = "Modified_Manifest_MainAttributes.jar"; - Support_Resources.copyFile(resources, null, modifiedJarName); - JarFile jarFile = new JarFile(new File(resources, modifiedJarName), - true); - Enumeration<JarEntry> entries = jarFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry zipEntry = entries.nextElement(); - try { - jarFile.getInputStream(zipEntry); - fail("SecurityException expected"); - } catch (SecurityException e) { - // desired - } - } - } - - /* - * It is all right in our original JarFile. If the Entry Attributes, for - * example Test.class in our jar, the jarFile.getInputStream will throw - * Security Exception. - */ - public void test_JarFile_Modified_Manifest_EntryAttributes() - throws IOException { - String modifiedJarName = "Modified_Manifest_EntryAttributes.jar"; - Support_Resources.copyFile(resources, null, modifiedJarName); - JarFile jarFile = new JarFile(new File(resources, modifiedJarName), - true); - Enumeration<JarEntry> entries = jarFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry zipEntry = entries.nextElement(); - try { - jarFile.getInputStream(zipEntry); - fail("should throw Security Exception"); - } catch (SecurityException e) { - // desired - } - } - } - - /* - * If the content of the .SA file is modified, no matter what it resides, - * JarFile.getInputStream of any JarEntry will throw Security Exception. - */ - public void test_JarFile_Modified_SF_EntryAttributes() throws IOException { - String modifiedJarName = "Modified_SF_EntryAttributes.jar"; - Support_Resources.copyFile(resources, null, modifiedJarName); - JarFile jarFile = new JarFile(new File(resources, modifiedJarName), - true); - Enumeration<JarEntry> entries = jarFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry zipEntry = entries.nextElement(); - try { - jarFile.getInputStream(zipEntry); - fail("should throw Security Exception"); - } catch (SecurityException e) { - // desired - } - } - } - - public void test_close() throws IOException { - String modifiedJarName = "Modified_SF_EntryAttributes.jar"; - Support_Resources.copyFile(resources, null, modifiedJarName); - JarFile jarFile = new JarFile(new File(resources, modifiedJarName), - true); - Enumeration<JarEntry> entries = jarFile.entries(); - - jarFile.close(); - jarFile.close(); - - // Can not check IOException - } - - /** - * @throws IOException - * java.util.jar.JarFile#getInputStream(java.util.zip.ZipEntry) - */ - public void test_getInputStreamLjava_util_jar_JarEntry() throws IOException { - File localFile = null; - try { - Support_Resources.copyFile(resources, null, jarName); - localFile = new File(resources, jarName); - } catch (Exception e) { - fail("Failed to create local file: " + e); - } - - byte[] b = new byte[1024]; - try { - JarFile jf = new JarFile(localFile); - java.io.InputStream is = jf.getInputStream(jf.getEntry(entryName)); - // BEGIN android-removed - // jf.close(); - // END android-removed - assertTrue("Returned invalid stream", is.available() > 0); - int r = is.read(b, 0, 1024); - is.close(); - StringBuffer sb = new StringBuffer(r); - for (int i = 0; i < r; i++) { - sb.append((char) (b[i] & 0xff)); - } - String contents = sb.toString(); - assertTrue("Incorrect stream read", contents.indexOf("bar") > 0); - // BEGIN android-added - jf.close(); - // END android-added - } catch (Exception e) { - fail("Exception during test: " + e.toString()); - } - - try { - JarFile jf = new JarFile(localFile); - InputStream in = jf.getInputStream(new JarEntry("invalid")); - assertNull("Got stream for non-existent entry", in); - } catch (Exception e) { - fail("Exception during test 2: " + e); - } - - try { - Support_Resources.copyFile(resources, null, jarName); - File signedFile = new File(resources, jarName); - JarFile jf = new JarFile(signedFile); - JarEntry jre = new JarEntry("foo/bar/A.class"); - jf.getInputStream(jre); - // InputStream returned in any way, exception can be thrown in case - // of reading from this stream only. - // fail("Should throw ZipException"); - } catch (ZipException ee) { - // expected - } - - try { - Support_Resources.copyFile(resources, null, jarName); - File signedFile = new File(resources, jarName); - JarFile jf = new JarFile(signedFile); - JarEntry jre = new JarEntry("foo/bar/A.class"); - jf.close(); - jf.getInputStream(jre); - // InputStream returned in any way, exception can be thrown in case - // of reading from this stream only. - // The same for IOException - fail("Should throw IllegalStateException"); - } catch (IllegalStateException ee) { - // expected - } - } - - /** - * The jar is intact, but the entry object is modified. - */ - // Regression test for issue introduced by HARMONY-4569: signed archives containing files with size 0 could not get verified. - public void testJarVerificationEmptyEntry() throws IOException { - Support_Resources.copyFile(resources, null, emptyEntryJar); - File f = new File(resources, emptyEntryJar); - - JarFile jarFile = new JarFile(f); - - ZipEntry zipEntry = jarFile.getJarEntry(emptyEntry1); - int res = jarFile.getInputStream(zipEntry).read(new byte[100], 0, 100); - assertEquals("Wrong length of empty jar entry", -1, res); - - zipEntry = jarFile.getJarEntry(emptyEntry2); - res = jarFile.getInputStream(zipEntry).read(new byte[100], 0, 100); - assertEquals("Wrong length of empty jar entry", -1, res); - - zipEntry = jarFile.getJarEntry(emptyEntry3); - res = jarFile.getInputStream(zipEntry).read(); - assertEquals("Wrong length of empty jar entry", -1, res); - } -} diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipFileTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipFileTest.java deleted file mode 100644 index a423f22..0000000 --- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipFileTest.java +++ /dev/null @@ -1,505 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.harmony.archive.tests.java.util.zip; - -import tests.support.Support_PlatformFile; -import tests.support.resource.Support_Resources; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.FilePermission; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.Permission; -import java.util.Enumeration; -import java.util.zip.ZipEntry; -import java.util.zip.ZipException; -import java.util.zip.ZipFile; -import libcore.java.lang.ref.FinalizationTester; - -public class ZipFileTest extends junit.framework.TestCase { - - public byte[] getAllBytesFromStream(InputStream is) throws IOException { - ByteArrayOutputStream bs = new ByteArrayOutputStream(); - byte[] buf = new byte[512]; - int iRead; - int off; - while (is.available() > 0) { - iRead = is.read(buf, 0, buf.length); - if (iRead > 0) bs.write(buf, 0, iRead); - } - return bs.toByteArray(); - } - - // the file hyts_zipFile.zip in setup must be included as a resource - private String tempFileName; - - private ZipFile zfile; - - // custom security manager - SecurityManager sm = new SecurityManager() { - final String forbidenPermissionAction = "read"; - - - - public void checkPermission(Permission perm) { - // only check if it's a FilePermission because Locale checks - // for a PropertyPermission with action"read" to get system props. - if (perm instanceof FilePermission - && perm.getActions().equals(forbidenPermissionAction)) { - throw new SecurityException(); - } - } - }; - - /** - * java.util.zip.ZipFile#ZipFile(java.io.File) - */ - public void test_ConstructorLjava_io_File() { - // Test for method java.util.zip.ZipFile(java.io.File) - assertTrue("Used to test", true); - } - - /** - * java.util.zip.ZipFile#ZipFile(java.io.File, int) - */ - public void test_ConstructorLjava_io_FileI() throws IOException { - zfile.close(); // about to reopen the same temp file - File file = new File(tempFileName); - ZipFile zip = new ZipFile(file, ZipFile.OPEN_DELETE | ZipFile.OPEN_READ); - zip.close(); - assertTrue("Zip should not exist", !file.exists()); - file = new File(tempFileName); - file.delete(); - try { - zip = new ZipFile(file, ZipFile.OPEN_READ); - fail("IOException expected"); - } catch (IOException ee) { - // expected - } - file = new File(tempFileName); - try { - zip = new ZipFile(file, -1); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException ee) { - // expected - } - } - - /** - * @throws IOException - * java.util.zip.ZipFile#ZipFile(java.lang.String) - */ - public void test_ConstructorLjava_lang_String() throws IOException { - System.setProperty("user.dir", System.getProperty("java.io.tmpdir")); - - zfile.close(); // about to reopen the same temp file - ZipFile zip = new ZipFile(tempFileName); - zip.close(); - File file = File.createTempFile("zip", "tmp"); - try { - zip = new ZipFile(file.getName()); - fail("ZipException expected"); - } catch (ZipException ee) { - // expected - } - file.delete(); - } - - protected ZipEntry test_finalize1(ZipFile zip) { - return zip.getEntry("File1.txt"); - } - - protected ZipFile test_finalize2(File file) throws IOException { - return new ZipFile(file); - } - - /** - * java.util.zip.ZipFile#finalize() - */ - public void test_finalize() throws IOException { - InputStream in = Support_Resources.getStream("hyts_ZipFile.zip"); - File file = Support_Resources.createTempFile(".jar"); - OutputStream out = new FileOutputStream(file); - int result; - byte[] buf = new byte[4096]; - while ((result = in.read(buf)) != -1) { - out.write(buf, 0, result); - } - in.close(); - out.close(); - /* - * ZipFile zip = new ZipFile(file); ZipEntry entry1 = - * zip.getEntry("File1.txt"); assertNotNull("Did not find entry", - * entry1); entry1 = null; zip = null; - */ - - assertNotNull("Did not find entry", test_finalize1(test_finalize2(file))); - FinalizationTester.induceFinalization(); - file.delete(); - assertTrue("Zip should not exist", !file.exists()); - } - - /** - * @throws IOException - * java.util.zip.ZipFile#close() - */ - public void test_close() throws IOException { - // Test for method void java.util.zip.ZipFile.close() - File fl = new File(tempFileName); - ZipFile zf = new ZipFile(fl); - InputStream is1 = zf.getInputStream(zf.getEntry("File1.txt")); - InputStream is2 = zf.getInputStream(zf.getEntry("File2.txt")); - - is1.read(); - is2.read(); - - zf.close(); - - try { - is1.read(); - fail("IOException expected"); - } catch (IOException ee) { - // expected - } - - try { - is2.read(); - fail("IOException expected"); - } catch (IOException ee) { - // expected - } - } - - /** - * java.util.zip.ZipFile#entries() - */ - public void test_entries() throws Exception { - // Test for method java.util.Enumeration java.util.zip.ZipFile.entries() - Enumeration<? extends ZipEntry> enumer = zfile.entries(); - int c = 0; - while (enumer.hasMoreElements()) { - ++c; - enumer.nextElement(); - } - assertTrue("Incorrect number of entries returned: " + c, c == 6); - - Enumeration<? extends ZipEntry> enumeration = zfile.entries(); - zfile.close(); - try { - enumeration.nextElement(); - fail("did not detect closed file"); - } catch (IllegalStateException expected) { - } - - try { - enumeration.hasMoreElements(); - fail("did not detect closed file"); - } catch (IllegalStateException expected) { - } - - try { - zfile.entries(); - fail("did not detect closed file"); - } catch (IllegalStateException expected) { - } - } - - /** - * java.util.zip.ZipFile#getEntry(java.lang.String) - */ - public void test_getEntryLjava_lang_String() throws IOException { - // Test for method java.util.zip.ZipEntry - // java.util.zip.ZipFile.getEntry(java.lang.String) - java.util.zip.ZipEntry zentry = zfile.getEntry("File1.txt"); - assertNotNull("Could not obtain ZipEntry", zentry); - int r; - InputStream in; - - zentry = zfile.getEntry("testdir1/File1.txt"); - assertNotNull("Could not obtain ZipEntry: testdir1/File1.txt", zentry); - zentry = zfile.getEntry("testdir1/"); - assertNotNull("Could not obtain ZipEntry: testdir1/", zentry); - in = zfile.getInputStream(zentry); - assertNotNull("testdir1/ should not have null input stream", in); - r = in.read(); - in.close(); - assertEquals("testdir1/ should not contain data", -1, r); - - zentry = zfile.getEntry("testdir1/testdir1"); - assertNotNull("Could not obtain ZipEntry: testdir1/testdir1", zentry); - in = zfile.getInputStream(zentry); - byte[] buf = new byte[256]; - r = in.read(buf); - in.close(); - assertEquals("incorrect contents", "This is also text", new String(buf, - 0, r)); - } - - public void test_getEntryLjava_lang_String_AndroidOnly() throws IOException { - java.util.zip.ZipEntry zentry = zfile.getEntry("File1.txt"); - assertNotNull("Could not obtain ZipEntry", zentry); - int r; - InputStream in; - - zentry = zfile.getEntry("testdir1"); - assertNotNull("Must be able to obtain ZipEntry: testdir1", zentry); - in = zfile.getInputStream(zentry); - /* - * Android delivers empty InputStream, RI no InputStream at all. The - * spec doesn't clarify this, so we need to deal with both situations. - */ - int data = -1; - if (in != null) { - data = in.read(); - in.close(); - } - assertEquals("Must not be able to read directory data", -1, data); - } - - public void test_getEntryLjava_lang_String_Ex() throws IOException { - java.util.zip.ZipEntry zentry = zfile.getEntry("File1.txt"); - assertNotNull("Could not obtain ZipEntry", zentry); - - zfile.close(); - try { - zfile.getEntry("File2.txt"); - fail("IllegalStateException expected"); - } catch (IllegalStateException ee) { - } - } - - /** - * @throws IOException - * java.util.zip.ZipFile#getInputStream(java.util.zip.ZipEntry) - */ - public void test_getInputStreamLjava_util_zip_ZipEntry() throws IOException { - // Test for method java.io.InputStream - // java.util.zip.ZipFile.getInputStream(java.util.zip.ZipEntry) - ZipEntry zentry = null; - InputStream is = null; - try { - zentry = zfile.getEntry("File1.txt"); - is = zfile.getInputStream(zentry); - byte[] rbuf = new byte[1000]; - int r; - is.read(rbuf, 0, r = (int) zentry.getSize()); - assertEquals("getInputStream read incorrect data", "This is text", - new String(rbuf, 0, r)); - } catch (java.io.IOException e) { - fail("IOException during getInputStream"); - } finally { - try { - is.close(); - } catch (java.io.IOException e) { - fail("Failed to close input stream"); - } - } - - zentry = zfile.getEntry("File2.txt"); - zfile.close(); - try { - is = zfile.getInputStream(zentry); - fail("IllegalStateException expected"); - } catch (IllegalStateException ee) { - // expected - } - - // ZipException can not be checked. Stream object returned or null. - } - - /** - * java.util.zip.ZipFile#getName() - */ - public void test_getName() { - // Test for method java.lang.String java.util.zip.ZipFile.getName() - assertTrue("Returned incorrect name: " + zfile.getName(), zfile - .getName().equals(tempFileName)); - } - - /** - * @throws IOException - * java.util.zip.ZipFile#size() - */ - public void test_size() throws IOException { - assertEquals(6, zfile.size()); - zfile.close(); - try { - zfile.size(); - fail("IllegalStateException expected"); - } catch (IllegalStateException expected) { - } - } - - /** - * java.io.InputStream#reset() - */ - public void test_reset() throws IOException { - // read an uncompressed entry - ZipEntry zentry = zfile.getEntry("File1.txt"); - InputStream is = zfile.getInputStream(zentry); - byte[] rbuf1 = new byte[6]; - byte[] rbuf2 = new byte[6]; - int r1, r2; - r1 = is.read(rbuf1); - assertEquals(rbuf1.length, r1); - r2 = is.read(rbuf2); - assertEquals(rbuf2.length, r2); - - try { - is.reset(); - fail(); - } catch (IOException expected) { - } - is.close(); - - // read a compressed entry - byte[] rbuf3 = new byte[4185]; - ZipEntry zentry2 = zfile.getEntry("File3.txt"); - is = zfile.getInputStream(zentry2); - r1 = is.read(rbuf3); - assertEquals(4183, r1); - try { - is.reset(); - fail(); - } catch (IOException expected) { - } - is.close(); - - is = zfile.getInputStream(zentry2); - r1 = is.read(rbuf3, 0, 3000); - assertEquals(3000, r1); - try { - is.reset(); - fail(); - } catch (IOException expected) { - } - is.close(); - } - - /** - * java.io.InputStream#reset() - */ - public void test_reset_subtest0() throws IOException { - // read an uncompressed entry - ZipEntry zentry = zfile.getEntry("File1.txt"); - InputStream is = zfile.getInputStream(zentry); - byte[] rbuf1 = new byte[12]; - byte[] rbuf2 = new byte[12]; - int r = is.read(rbuf1, 0, 4); - assertEquals(4, r); - is.mark(0); - r = is.read(rbuf1); - assertEquals(8, r); - assertEquals(-1, is.read()); - - try { - is.reset(); - fail(); - } catch (IOException expected) { - } - - is.close(); - - // read a compressed entry - byte[] rbuf3 = new byte[4185]; - ZipEntry zentry2 = zfile.getEntry("File3.txt"); - is = zfile.getInputStream(zentry2); - r = is.read(rbuf3, 0, 3000); - assertEquals(3000, r); - is.mark(0); - r = is.read(rbuf3); - assertEquals(1183, r); - assertEquals(-1, is.read()); - - try { - is.reset(); - fail(); - } catch (IOException expected) { - } - - is.close(); - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - @Override - protected void setUp() { - try { - // Create a local copy of the file since some tests want to alter - // information. - tempFileName = System.getProperty("java.io.tmpdir"); - String separator = System.getProperty("file.separator"); - if (tempFileName.charAt(tempFileName.length() - 1) == separator - .charAt(0)) { - tempFileName = Support_PlatformFile.getNewPlatformFile( - tempFileName, "gabba.zip"); - } else { - tempFileName = Support_PlatformFile.getNewPlatformFile( - tempFileName + separator, "gabba.zip"); - } - - File f = new File(tempFileName); - f.delete(); - InputStream is = Support_Resources.getStream("hyts_ZipFile.zip"); - FileOutputStream fos = new FileOutputStream(f); - byte[] rbuf = getAllBytesFromStream(is); - fos.write(rbuf, 0, rbuf.length); - is.close(); - fos.close(); - zfile = new ZipFile(f); - } catch (Exception e) { - System.out.println("Exception during ZipFile setup:"); - e.printStackTrace(); - } - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - @Override - protected void tearDown() { - try { - if (zfile != null) { - // Note zfile is a user-defined zip file used by other tests and - // should not be deleted - zfile.close(); - tempFileName = System.getProperty("java.io.tmpdir"); - String separator = System.getProperty("file.separator"); - if (tempFileName.charAt(tempFileName.length() - 1) == separator - .charAt(0)) { - tempFileName = Support_PlatformFile.getNewPlatformFile( - tempFileName, "gabba.zip"); - } else { - tempFileName = Support_PlatformFile.getNewPlatformFile( - tempFileName + separator, "gabba.zip"); - } - - File f = new File(tempFileName); - f.delete(); - } - } catch (Exception e) { - } - } - -} diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/ExemptionMechanismTest.java b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/ExemptionMechanismTest.java index f617adb..87b2913 100644 --- a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/ExemptionMechanismTest.java +++ b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/ExemptionMechanismTest.java @@ -17,8 +17,6 @@ package org.apache.harmony.crypto.tests.javax.crypto; -import dalvik.annotation.SideEffect; - import java.math.BigInteger; import java.security.AlgorithmParameters; import java.security.InvalidAlgorithmParameterException; @@ -186,7 +184,7 @@ public class ExemptionMechanismTest extends TestCase { } } - @SideEffect("Causes OutOfMemoryError to test finalization") + // Side Effect: Causes OutOfMemoryError to test finalization public void test_finalize () { Mock_ExemptionMechanism mem = new Mock_ExemptionMechanism(null, null, "Name"); assertNotNull(mem); diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/KeyAgreementTest.java b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/KeyAgreementTest.java index 99d127a..0642229 100644 --- a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/KeyAgreementTest.java +++ b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/KeyAgreementTest.java @@ -22,6 +22,8 @@ package org.apache.harmony.crypto.tests.javax.crypto; +import org.apache.harmony.security.tests.support.SpiEngUtils; +import org.apache.harmony.security.tests.support.TestKeyPair; import java.math.BigInteger; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; @@ -31,6 +33,7 @@ import java.security.PrivateKey; import java.security.Provider; import java.security.PublicKey; import java.security.SecureRandom; +import java.security.Security; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.DSAParameterSpec; import java.security.spec.RSAKeyGenParameterSpec; @@ -40,12 +43,10 @@ import javax.crypto.KeyAgreementSpi; import javax.crypto.ShortBufferException; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.spec.DHParameterSpec; - -import org.apache.harmony.crypto.tests.support.MyKeyAgreementSpi; -import org.apache.harmony.security.tests.support.SpiEngUtils; -import org.apache.harmony.security.tests.support.TestKeyPair; - import junit.framework.TestCase; +import libcore.java.security.StandardNames; +import libcore.javax.crypto.MockKey; +import libcore.javax.crypto.MockKey2; /** @@ -676,4 +677,127 @@ public class KeyAgreementTest extends TestCase { //expected } } + + private static abstract class MockProvider extends Provider { + public MockProvider(String name) { + super(name, 1.0, "Mock provider used for testing"); + setup(); + } + + public abstract void setup(); + } + + public void testKeyAgreement_getInstance_SuppliedProviderNotRegistered_Success() + throws Exception { + Provider mockProvider = new MockProvider("MockProvider") { + public void setup() { + put("KeyAgreement.FOO", MockKeyAgreementSpi.AllKeyTypes.class.getName()); + } + }; + + { + KeyAgreement s = KeyAgreement.getInstance("FOO", mockProvider); + s.init(new MockKey()); + assertEquals(mockProvider, s.getProvider()); + } + } + + public void testKeyAgreement_getInstance_OnlyUsesSpecifiedProvider_SameNameAndClass_Success() + throws Exception { + Provider mockProvider = new MockProvider("MockProvider") { + public void setup() { + put("KeyAgreement.FOO", MockKeyAgreementSpi.AllKeyTypes.class.getName()); + } + }; + + Security.addProvider(mockProvider); + try { + { + Provider mockProvider2 = new MockProvider("MockProvider") { + public void setup() { + put("KeyAgreement.FOO", MockKeyAgreementSpi.AllKeyTypes.class.getName()); + } + }; + KeyAgreement s = KeyAgreement.getInstance("FOO", mockProvider2); + assertEquals(mockProvider2, s.getProvider()); + } + } finally { + Security.removeProvider(mockProvider.getName()); + } + } + + public void testKeyAgreement_getInstance_DelayedInitialization_KeyType() throws Exception { + Provider mockProviderSpecific = new MockProvider("MockProviderSpecific") { + public void setup() { + put("KeyAgreement.FOO", MockKeyAgreementSpi.SpecificKeyTypes.class.getName()); + put("KeyAgreement.FOO SupportedKeyClasses", MockKey.class.getName()); + } + }; + Provider mockProviderSpecific2 = new MockProvider("MockProviderSpecific2") { + public void setup() { + put("KeyAgreement.FOO", MockKeyAgreementSpi.SpecificKeyTypes2.class.getName()); + put("KeyAgreement.FOO SupportedKeyClasses", MockKey2.class.getName()); + } + }; + Provider mockProviderAll = new MockProvider("MockProviderAll") { + public void setup() { + put("KeyAgreement.FOO", MockKeyAgreementSpi.AllKeyTypes.class.getName()); + } + }; + + Security.addProvider(mockProviderSpecific); + Security.addProvider(mockProviderSpecific2); + Security.addProvider(mockProviderAll); + + try { + { + KeyAgreement s = KeyAgreement.getInstance("FOO"); + s.init(new MockKey()); + assertEquals(mockProviderSpecific, s.getProvider()); + + try { + s.init(new MockKey2()); + assertEquals(mockProviderSpecific2, s.getProvider()); + if (StandardNames.IS_RI) { + fail("RI was broken before; fix tests now that it works!"); + } + } catch (InvalidKeyException e) { + if (!StandardNames.IS_RI) { + fail("Non-RI should select the right provider"); + } + } + } + + { + KeyAgreement s = KeyAgreement.getInstance("FOO"); + s.init(new PrivateKey() { + @Override + public String getAlgorithm() { + throw new UnsupportedOperationException("not implemented"); + } + + @Override + public String getFormat() { + throw new UnsupportedOperationException("not implemented"); + } + + @Override + public byte[] getEncoded() { + throw new UnsupportedOperationException("not implemented"); + } + }); + assertEquals(mockProviderAll, s.getProvider()); + } + + { + KeyAgreement s = KeyAgreement.getInstance("FOO"); + assertEquals(mockProviderSpecific, s.getProvider()); + } + } finally { + Security.removeProvider(mockProviderSpecific.getName()); + Security.removeProvider(mockProviderSpecific2.getName()); + Security.removeProvider(mockProviderAll.getName()); + } + } + } diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MacTest.java b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MacTest.java index b1559f5..ddd0695 100644 --- a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MacTest.java +++ b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MacTest.java @@ -27,26 +27,26 @@ import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; +import java.security.PrivateKey; import java.security.Provider; import java.security.Security; import java.security.spec.PSSParameterSpec; +import java.util.ArrayList; import java.util.Arrays; - import javax.crypto.Mac; import javax.crypto.MacSpi; import javax.crypto.SecretKey; import javax.crypto.ShortBufferException; import javax.crypto.spec.DHGenParameterSpec; - import javax.crypto.spec.SecretKeySpec; - import org.apache.harmony.crypto.tests.support.MyMacSpi; import org.apache.harmony.security.tests.support.SpiEngUtils; - import junit.framework.TestCase; - import junit.framework.Test; import junit.framework.TestSuite; +import libcore.java.security.StandardNames; +import libcore.javax.crypto.MockKey; +import libcore.javax.crypto.MockKey2; /** * Tests for Mac class constructors and methods @@ -71,7 +71,7 @@ public class MacTest extends TestCase { private static String[] validValues = new String[3]; public static final String validAlgorithmsMac [] = - {"HmacSHA1", "HmacMD5", "HmacSHA256", "HmacSHA384", "HmacSHA512"}; + {"HmacSHA1", "HmacMD5", "HmacSHA224", "HmacSHA256", "HmacSHA384", "HmacSHA512"}; static { @@ -90,20 +90,19 @@ public class MacTest extends TestCase { } } - private Mac [] createMacs() { + private Mac[] createMacs() throws Exception { if (!DEFSupported) { fail(NotSupportedMsg); return null; } - try { - Mac m [] = new Mac[3]; - m[0] = Mac.getInstance(defaultAlgorithm); - m[1] = Mac.getInstance(defaultAlgorithm, defaultProvider); - m[2] = Mac.getInstance(defaultAlgorithm, defaultProviderName); - return m; - } catch (Exception e) { - return null; + ArrayList<Mac> macList = new ArrayList<Mac>(); + macList.add(Mac.getInstance(defaultAlgorithm)); + macList.add(Mac.getInstance(defaultAlgorithm, defaultProvider)); + macList.add(Mac.getInstance(defaultAlgorithm, defaultProviderName)); + for (Provider p : Security.getProviders("Mac." + defaultAlgorithm)) { + macList.add(Mac.getInstance(defaultAlgorithm, p)); } + return macList.toArray(new Mac[macList.size()]); } /** @@ -356,9 +355,7 @@ public class MacTest extends TestCase { * throws ShotBufferException when outOffset is negative or * outOffset >= output.length or when given buffer is small */ - public void testMac10() throws NoSuchAlgorithmException, - NoSuchProviderException, IllegalArgumentException, - IllegalStateException, InvalidKeyException { + public void testMac10() throws Exception { if (!DEFSupported) { fail(NotSupportedMsg); return; @@ -404,9 +401,7 @@ public class MacTest extends TestCase { * <code>doFinal()</code> methods Assertion: Mac result is stored in * output buffer */ - public void testMac11() throws NoSuchAlgorithmException, NoSuchProviderException, - IllegalArgumentException, IllegalStateException, - InvalidKeyException, ShortBufferException { + public void testMac11() throws Exception { if (!DEFSupported) { fail(NotSupportedMsg); return; @@ -430,9 +425,7 @@ public class MacTest extends TestCase { * Test for <code>doFinal(byte[] input)</code> method * Assertion: update Mac and returns result */ - public void testMac12() throws NoSuchAlgorithmException, NoSuchProviderException, - IllegalArgumentException, IllegalStateException, - InvalidKeyException { + public void testMac12() throws Exception { if (!DEFSupported) { fail(NotSupportedMsg); return; @@ -447,15 +440,15 @@ public class MacTest extends TestCase { byte[] res1 = macs[i].doFinal(); byte[] res2 = macs[i].doFinal(); assertEquals("Results are not the same", - IntegralToString.bytesToHexString(res1, false), - IntegralToString.bytesToHexString(res2, false)); + Arrays.toString(res1), + Arrays.toString(res2)); res2 = macs[i].doFinal(upd); macs[i].update(upd); res1 = macs[i].doFinal(); assertEquals("Results are not the same", - IntegralToString.bytesToHexString(res1, false), - IntegralToString.bytesToHexString(res2, false)); + Arrays.toString(res1), + Arrays.toString(res2)); } } @@ -464,9 +457,7 @@ public class MacTest extends TestCase { * Assertion: throws IllegalArgumentException when offset or len is negative, * offset + len >= input.length */ - public void testMac13() throws NoSuchAlgorithmException, - NoSuchProviderException, IllegalArgumentException, IllegalStateException, - InvalidKeyException { + public void testMac13() throws Exception { if (!DEFSupported) { fail(NotSupportedMsg); return; @@ -505,9 +496,7 @@ public class MacTest extends TestCase { * methods * Assertion: updates Mac */ - public void testMac14() throws NoSuchAlgorithmException, - NoSuchProviderException, IllegalArgumentException, IllegalStateException, - InvalidKeyException { + public void testMac14() throws Exception { if (!DEFSupported) { fail(NotSupportedMsg); return; @@ -547,7 +536,7 @@ public class MacTest extends TestCase { * Test for <code>clone()</code> method * Assertion: returns Mac object or throws CloneNotSupportedException */ - public void testMacClone() throws NoSuchAlgorithmException, CloneNotSupportedException { + public void testMacClone() throws Exception { if (!DEFSupported) { fail(NotSupportedMsg); return; @@ -572,9 +561,7 @@ public class MacTest extends TestCase { * Assertion: throws InvalidKeyException and InvalidAlgorithmParameterException * when parameters are not appropriate */ - public void testInit() throws NoSuchAlgorithmException, NoSuchProviderException, - IllegalArgumentException, IllegalStateException, InvalidAlgorithmParameterException, - InvalidKeyException { + public void testInit() throws Exception { if (!DEFSupported) { fail(NotSupportedMsg); return; @@ -588,6 +575,7 @@ public class MacTest extends TestCase { SecretKeySpec sks1 = new SecretKeySpec(b, "RSA"); for (int i = 0; i < macs.length; i++) { + macs[i].reset(); macs[i].init(sks); try { macs[i].init(sks1, algPSS); @@ -621,9 +609,7 @@ public class MacTest extends TestCase { * methods * Assertion: processes Mac; if input is null then do nothing */ - public void testUpdateByteBuffer01() throws NoSuchAlgorithmException, NoSuchProviderException, - IllegalArgumentException, IllegalStateException, InvalidAlgorithmParameterException, - InvalidKeyException { + public void testUpdateByteBuffer01() throws Exception { if (!DEFSupported) { fail(NotSupportedMsg); return; @@ -664,9 +650,7 @@ public class MacTest extends TestCase { * methods * Assertion: processes Mac */ - public void testUpdateByteBuffer02() throws NoSuchAlgorithmException, NoSuchProviderException, - IllegalArgumentException, IllegalStateException, InvalidAlgorithmParameterException, - InvalidKeyException { + public void testUpdateByteBuffer02() throws Exception { if (!DEFSupported) { fail(NotSupportedMsg); return; @@ -699,7 +683,7 @@ public class MacTest extends TestCase { * Test for <code>clone()</code> method * Assertion: clone if provider is clo */ - public void testClone() { + public void testClone() throws Exception { if (!DEFSupported) { fail(NotSupportedMsg); return; @@ -720,7 +704,7 @@ public class MacTest extends TestCase { * Test for <code>getMacLength()</code> method * Assertion: return Mac length */ - public void testGetMacLength() { + public void testGetMacLength() throws Exception { if (!DEFSupported) { fail(NotSupportedMsg); return; @@ -736,7 +720,7 @@ public class MacTest extends TestCase { * Test for <code>reset()</code> method * Assertion: return Mac length */ - public void testReset() throws InvalidKeyException { + public void testReset() throws Exception { if (!DEFSupported) { fail(NotSupportedMsg); return; @@ -781,15 +765,14 @@ public class MacTest extends TestCase { } MacSpi spi = new MyMacSpi(); Mac mac = new myMac(spi, defaultProvider, defaultAlgorithm); - assertEquals("Incorrect algorithm", mac.getAlgorithm(), - defaultAlgorithm); - assertEquals("Incorrect provider", mac.getProvider(), defaultProvider); + assertEquals("Incorrect algorithm", defaultAlgorithm, mac.getAlgorithm()); + assertEquals("Incorrect provider", defaultProvider, mac.getProvider()); try { mac.init(null, null); fail("Exception should be thrown because init(..) uses incorrect parameters"); } catch (Exception e) { } - assertEquals("Invalid mac length", mac.getMacLength(), 0); + assertEquals("Invalid mac length", 0, mac.getMacLength()); mac = new myMac(null, null, null); assertNull("Algorithm must be null", mac.getAlgorithm()); @@ -892,6 +875,127 @@ public class MacTest extends TestCase { } } + private static abstract class MockProvider extends Provider { + public MockProvider(String name) { + super(name, 1.0, "Mock provider used for testing"); + setup(); + } + + public abstract void setup(); + } + + public void testMac_getInstance_SuppliedProviderNotRegistered_Success() throws Exception { + Provider mockProvider = new MockProvider("MockProvider") { + public void setup() { + put("Mac.FOO", MockMacSpi.AllKeyTypes.class.getName()); + } + }; + + { + Mac s = Mac.getInstance("FOO", mockProvider); + s.init(new MockKey()); + assertEquals(mockProvider, s.getProvider()); + } + } + + public void testMac_getInstance_OnlyUsesSpecifiedProvider_SameNameAndClass_Success() + throws Exception { + Provider mockProvider = new MockProvider("MockProvider") { + public void setup() { + put("Mac.FOO", MockMacSpi.AllKeyTypes.class.getName()); + } + }; + + Security.addProvider(mockProvider); + try { + { + Provider mockProvider2 = new MockProvider("MockProvider") { + public void setup() { + put("Mac.FOO", MockMacSpi.AllKeyTypes.class.getName()); + } + }; + Mac s = Mac.getInstance("FOO", mockProvider2); + assertEquals(mockProvider2, s.getProvider()); + } + } finally { + Security.removeProvider(mockProvider.getName()); + } + } + + public void testMac_getInstance_DelayedInitialization_KeyType() throws Exception { + Provider mockProviderSpecific = new MockProvider("MockProviderSpecific") { + public void setup() { + put("Mac.FOO", MockMacSpi.SpecificKeyTypes.class.getName()); + put("Mac.FOO SupportedKeyClasses", MockKey.class.getName()); + } + }; + Provider mockProviderSpecific2 = new MockProvider("MockProviderSpecific2") { + public void setup() { + put("Mac.FOO", MockMacSpi.SpecificKeyTypes2.class.getName()); + put("Mac.FOO SupportedKeyClasses", MockKey2.class.getName()); + } + }; + Provider mockProviderAll = new MockProvider("MockProviderAll") { + public void setup() { + put("Mac.FOO", MockMacSpi.AllKeyTypes.class.getName()); + } + }; + + Security.addProvider(mockProviderSpecific); + Security.addProvider(mockProviderSpecific2); + Security.addProvider(mockProviderAll); + + try { + { + Mac s = Mac.getInstance("FOO"); + s.init(new MockKey()); + assertEquals(mockProviderSpecific, s.getProvider()); + + try { + s.init(new MockKey2()); + assertEquals(mockProviderSpecific2, s.getProvider()); + if (StandardNames.IS_RI) { + fail("RI was broken before; fix tests now that it works!"); + } + } catch (InvalidKeyException e) { + if (!StandardNames.IS_RI) { + fail("Non-RI should select the right provider"); + } + } + } + + { + Mac s = Mac.getInstance("FOO"); + s.init(new PrivateKey() { + @Override + public String getAlgorithm() { + throw new UnsupportedOperationException("not implemented"); + } + + @Override + public String getFormat() { + throw new UnsupportedOperationException("not implemented"); + } + + @Override + public byte[] getEncoded() { + throw new UnsupportedOperationException("not implemented"); + } + }); + assertEquals(mockProviderAll, s.getProvider()); + } + + { + Mac s = Mac.getInstance("FOO"); + assertEquals(mockProviderSpecific, s.getProvider()); + } + } finally { + Security.removeProvider(mockProviderSpecific.getName()); + Security.removeProvider(mockProviderSpecific2.getName()); + Security.removeProvider(mockProviderAll.getName()); + } + } + public static Test suite() { return new TestSuite(MacTest.class); } diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MockKeyAgreementSpi.java b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MockKeyAgreementSpi.java new file mode 100644 index 0000000..4b53a6b --- /dev/null +++ b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MockKeyAgreementSpi.java @@ -0,0 +1,89 @@ +/* + * Copyright 2014 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 org.apache.harmony.crypto.tests.javax.crypto; + +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.spec.AlgorithmParameterSpec; +import javax.crypto.KeyAgreementSpi; +import javax.crypto.SecretKey; +import javax.crypto.ShortBufferException; +import libcore.javax.crypto.MockKey; +import libcore.javax.crypto.MockKey2; + +public class MockKeyAgreementSpi extends KeyAgreementSpi { + public static class SpecificKeyTypes extends MockKeyAgreementSpi { + @Override + public void checkKeyType(Key key) throws InvalidKeyException { + if (!(key instanceof MockKey)) { + throw new InvalidKeyException("Must be MockKey!"); + } + } + } + + public static class SpecificKeyTypes2 extends MockKeyAgreementSpi { + @Override + public void checkKeyType(Key key) throws InvalidKeyException { + if (!(key instanceof MockKey2)) { + throw new InvalidKeyException("Must be MockKey2!"); + } + } + } + + public static class AllKeyTypes extends MockKeyAgreementSpi { + } + + public void checkKeyType(Key key) throws InvalidKeyException { + } + + @Override + protected Key engineDoPhase(Key key, boolean lastPhase) throws InvalidKeyException, + IllegalStateException { + throw new UnsupportedOperationException(); + } + + @Override + protected byte[] engineGenerateSecret() throws IllegalStateException { + throw new UnsupportedOperationException(); + } + + @Override + protected int engineGenerateSecret(byte[] sharedSecret, int offset) + throws IllegalStateException, ShortBufferException { + throw new UnsupportedOperationException(); + } + + @Override + protected SecretKey engineGenerateSecret(String algorithm) throws IllegalStateException, + NoSuchAlgorithmException, InvalidKeyException { + throw new UnsupportedOperationException(); + } + + @Override + protected void engineInit(Key key, SecureRandom random) throws InvalidKeyException { + checkKeyType(key); + } + + @Override + protected void engineInit(Key key, AlgorithmParameterSpec params, SecureRandom random) + throws InvalidKeyException, InvalidAlgorithmParameterException { + checkKeyType(key); + } +} diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MockMacSpi.java b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MockMacSpi.java new file mode 100644 index 0000000..6a28fb3 --- /dev/null +++ b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MockMacSpi.java @@ -0,0 +1,82 @@ +/* + * Copyright 2014 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 org.apache.harmony.crypto.tests.javax.crypto; + +import java.security.InvalidKeyException; +import java.security.InvalidParameterException; +import java.security.Key; +import java.security.spec.AlgorithmParameterSpec; +import javax.crypto.MacSpi; +import libcore.javax.crypto.MockKey; +import libcore.javax.crypto.MockKey2; + +public class MockMacSpi extends MacSpi { + public static class SpecificKeyTypes extends MockMacSpi { + @Override + public void checkKeyType(Key key) throws InvalidKeyException { + if (!(key instanceof MockKey)) { + throw new InvalidKeyException("Must be MockKey!"); + } + } + } + + public static class SpecificKeyTypes2 extends MockMacSpi { + @Override + public void checkKeyType(Key key) throws InvalidKeyException { + if (!(key instanceof MockKey2)) { + throw new InvalidKeyException("Must be MockKey2!"); + } + } + } + + public static class AllKeyTypes extends MockMacSpi { + } + + public void checkKeyType(Key key) throws InvalidKeyException { + } + + @Override + protected int engineGetMacLength() { + throw new UnsupportedOperationException(); + } + + @Override + protected void engineInit(Key key, AlgorithmParameterSpec params) throws InvalidKeyException, + InvalidParameterException { + checkKeyType(key); + } + + @Override + protected void engineUpdate(byte input) { + throw new UnsupportedOperationException(); + } + + @Override + protected void engineUpdate(byte[] input, int offset, int len) { + throw new UnsupportedOperationException(); + } + + @Override + protected byte[] engineDoFinal() { + throw new UnsupportedOperationException(); + } + + @Override + protected void engineReset() { + throw new UnsupportedOperationException(); + } +} diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/SealedObjectTest.java b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/SealedObjectTest.java index 3ea57bf..5cbdab3 100644 --- a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/SealedObjectTest.java +++ b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/SealedObjectTest.java @@ -165,6 +165,34 @@ public class SealedObjectTest extends TestCase { + "in cipher.", algorithm, so.getAlgorithm()); } + // https://code.google.com/p/android/issues/detail?id=73235 + public void testGetAlgorithmAfterSerialization() throws Exception { + String secret = "secret string"; + String algorithm = "DES"; + KeyGenerator kg = KeyGenerator.getInstance(algorithm); + Key key = kg.generateKey(); + + Cipher cipher = Cipher.getInstance(algorithm); + cipher.init(Cipher.ENCRYPT_MODE, key); + SealedObject so = new SealedObject(secret, cipher); + + assertEquals("The algorithm name should be the same as used " + + "in cipher.", algorithm, so.getAlgorithm()); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(so); + oos.close(); + + ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); + SealedObject readSo = (SealedObject) ois.readObject(); + ois.close(); + + // Bug 73235 would swap the Cipher algorithm and parameters. Parameters is not public but + // algorithm is so we check that. + assertEquals(so.getAlgorithm(), readSo.getAlgorithm()); + } + /** * getObject(Key key) method testing. Tests if the object sealed with * encryption algorithm and specified parameters can be retrieved by diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherAesTest.java b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherAesTest.java index 0b8f017..85c2438 100644 --- a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherAesTest.java +++ b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherAesTest.java @@ -18,7 +18,7 @@ package org.apache.harmony.crypto.tests.javax.crypto.func; import junit.framework.TestCase; public class CipherAesTest extends TestCase { -// 216 cases checked +// 324 cases checked public void test_AesNoISO() { CipherSymmetricKeyThread aesNoISO = new CipherSymmetricKeyThread("AES", new int[] {128, 192, 256}, // Keysize must be 128, 192, 256. @@ -29,7 +29,8 @@ public class CipherAesTest extends TestCase { "CFB128", "OFB", "OFB8", "OFB16", "OFB24", "OFB32", "OFB40", "OFB48", "OFB56", "OFB64", "OFB72", "OFB80", "OFB88", "OFB96", "OFB104", "OFB112", "OFB120", - "OFB128"}, new String[] {"NoPadding", "PKCS5Padding"}); + "OFB128"}, + new String[] {"NoPadding", "PKCS5Padding", "PKCS7Padding"}); aesNoISO.launcher(); diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherDESedeTest.java b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherDESedeTest.java index d8565f1..c7b4f20 100644 --- a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherDESedeTest.java +++ b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherDESedeTest.java @@ -18,7 +18,7 @@ package org.apache.harmony.crypto.tests.javax.crypto.func; import junit.framework.TestCase; public class CipherDESedeTest extends TestCase { -// 80 cases checked +// 120 cases checked public void test_DESedeNoISO() { CipherSymmetricKeyThread DESedeNoISO = new CipherSymmetricKeyThread( "DESede", new int[] {112, 168},// Keysize must be 112 or 168. @@ -26,7 +26,8 @@ public class CipherDESedeTest extends TestCase { "ECB", "CBC", "CFB", "CFB8", "CFB16", "CFB24", "CFB32", "CFB40", "CFB48", "CFB56", "CFB64", "OFB", "OFB8", "OFB16", "OFB24", "OFB32", "OFB40", "OFB48", "OFB56", - "OFB64"}, new String[] {"NoPadding", "PKCS5Padding"}); + "OFB64"}, + new String[] {"NoPadding", "PKCS5Padding", "PKCS7Padding"}); DESedeNoISO.launcher(); diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/support/MyCipher.java b/luni/src/test/java/org/apache/harmony/crypto/tests/support/MyCipher.java index c9eb26e..ff4babc 100644 --- a/luni/src/test/java/org/apache/harmony/crypto/tests/support/MyCipher.java +++ b/luni/src/test/java/org/apache/harmony/crypto/tests/support/MyCipher.java @@ -52,7 +52,8 @@ public class MyCipher extends CipherSpi { @Override protected void engineSetPadding(String padding) throws NoSuchPaddingException { - if (!"PKCS5Padding".equals(padding)) { + if ((!"PKCS5Padding".equals(padding)) + && (!"PKCS7Padding".equals(padding))) { throw new NoSuchPaddingException(padding); } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/HttpURLConnectionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/HttpURLConnectionTest.java index 5d8c621..290ae9a 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/HttpURLConnectionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/HttpURLConnectionTest.java @@ -17,8 +17,6 @@ package org.apache.harmony.luni.tests.internal.net.www.protocol.http; -import dalvik.annotation.SideEffect; - import java.io.IOException; import java.net.Authenticator; import java.net.HttpURLConnection; @@ -270,7 +268,7 @@ public class HttpURLConnectionTest extends TestCase { ProxySelector.setDefault(defPS); } } - @SideEffect("Suffers from side effect of other, currently unknown test") + // SideEffect: Suffers from side effect of other, currently unknown test public void testProxyAuthorization() throws Exception { // Set up test Authenticator Authenticator.setDefault(new Authenticator() { diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java index c516f67..5258fd1 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java @@ -17,6 +17,12 @@ package org.apache.harmony.luni.tests.internal.net.www.protocol.https; +import com.google.mockwebserver.Dispatcher; +import com.google.mockwebserver.MockResponse; +import com.google.mockwebserver.MockWebServer; +import com.google.mockwebserver.RecordedRequest; +import com.google.mockwebserver.SocketPolicy; + import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; @@ -25,7 +31,6 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.io.PrintStream; import java.net.Authenticator; import java.net.InetSocketAddress; import java.net.PasswordAuthentication; @@ -36,20 +41,15 @@ import java.net.URL; import java.security.KeyStore; import java.security.cert.Certificate; import java.util.Arrays; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; +import java.util.Collections; +import java.util.LinkedList; + import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLServerSocket; import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; @@ -59,22 +59,26 @@ import libcore.javax.net.ssl.TestTrustManager; /** * Implementation independent test for HttpsURLConnection. - * The test needs certstore file placed in system classpath - * and named as "key_store." + the type of the - * default KeyStore installed in the system in lower case. - * <br> - * For example: if default KeyStore type in the system is BKS - * (i.e. java.security file sets up the property keystore.type=BKS), - * thus classpath should point to the directory with "key_store.bks" - * file. - * <br> - * This certstore file should contain self-signed certificate - * generated by keytool utility in a usual way. - * <br> - * The password to the certstore should be "password" (without quotes). */ public class HttpsURLConnectionTest extends TestCase { + private static final String POST_METHOD = "POST"; + + private static final String GET_METHOD = "GET"; + + /** + * Data to be posted by client to the server when the method is POST. + */ + private static final String POST_DATA = "_.-^ Client's Data ^-._"; + + /** + * The content of the response to be sent during HTTPS session. + */ + private static final String RESPONSE_CONTENT + = "<HTML>\n" + + "<HEAD><TITLE>HTTPS Response Content</TITLE></HEAD>\n" + + "</HTML>"; + // the password to the store private static final String KS_PASSWORD = "password"; @@ -107,7 +111,7 @@ public class HttpsURLConnectionTest extends TestCase { * Checks that HttpsURLConnection's default SSLSocketFactory is operable. */ public void testGetDefaultSSLSocketFactory() throws Exception { - // set up the properties defining the default values needed by SSL stuff + // set up the properties pointing to the key/trust stores setUpStoreProperties(); SSLSocketFactory defaultSSLSF = HttpsURLConnection.getDefaultSSLSocketFactory(); @@ -119,55 +123,58 @@ public class HttpsURLConnectionTest extends TestCase { } public void testHttpsConnection() throws Throwable { - // set up the properties defining the default values needed by SSL stuff + // set up the properties pointing to the key/trust stores setUpStoreProperties(); - // create the SSL server socket acting as a server SSLContext ctx = getContext(); - ServerSocket ss = ctx.getServerSocketFactory().createServerSocket(0); - // create the HostnameVerifier to check hostname verification - TestHostnameVerifier hnv = new TestHostnameVerifier(); - HttpsURLConnection.setDefaultHostnameVerifier(hnv); + // set the HostnameVerifier required to satisfy SSL - always returns "verified". + HttpsURLConnection.setDefaultHostnameVerifier(new TestHostnameVerifier()); + + // create a webserver to check and respond to requests + SingleRequestDispatcher dispatcher = new SingleRequestDispatcher(GET_METHOD, OK_CODE); + MockWebServer webServer = createWebServer(ctx, dispatcher); // create url connection to be tested - URL url = new URL("https://localhost:" + ss.getLocalPort()); + URL url = webServer.getUrl("/"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setSSLSocketFactory(ctx.getSocketFactory()); // perform the interaction between the peers - SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss); + executeClientRequest(connection, false /* doOutput */); - // check the connection state - checkConnectionStateParameters(connection, peerSocket); + checkConnectionStateParameters(connection, dispatcher.getLastRequest()); // should silently exit connection.connect(); + + webServer.shutdown(); } /** - * Tests the behaviour of HTTPS connection in case of unavailability - * of requested resource. + * Tests the behaviour of HTTPS connection in case of unavailability of requested resource. */ public void testHttpsConnection_Not_Found_Response() throws Throwable { - // set up the properties defining the default values needed by SSL stuff + // set up the properties pointing to the key/trust stores setUpStoreProperties(); - // create the SSL server socket acting as a server SSLContext ctx = getContext(); - ServerSocket ss = ctx.getServerSocketFactory().createServerSocket(0); - // create the HostnameVerifier to check hostname verification - TestHostnameVerifier hnv = new TestHostnameVerifier(); - HttpsURLConnection.setDefaultHostnameVerifier(hnv); + // set the HostnameVerifier required to satisfy SSL - always returns "verified". + HttpsURLConnection.setDefaultHostnameVerifier(new TestHostnameVerifier()); + + // create a webserver to check and respond to requests + SingleRequestDispatcher dispatcher = + new SingleRequestDispatcher(GET_METHOD, NOT_FOUND_CODE); + MockWebServer webServer = createWebServer(ctx, dispatcher); // create url connection to be tested - URL url = new URL("https://localhost:" + ss.getLocalPort()); + URL url = webServer.getUrl("/"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setSSLSocketFactory(ctx.getSocketFactory()); try { - doInteraction(connection, ss, NOT_FOUND_CODE); + executeClientRequest(connection, false /* doOutput */); fail("Expected exception was not thrown."); } catch (FileNotFoundException e) { if (DO_LOG) { @@ -178,94 +185,100 @@ public class HttpsURLConnectionTest extends TestCase { // should silently exit connection.connect(); + + webServer.shutdown(); } /** - * Tests possibility to set up the default SSLSocketFactory - * to be used by HttpsURLConnection. + * Tests possibility to set up the default SSLSocketFactory to be used by HttpsURLConnection. */ public void testSetDefaultSSLSocketFactory() throws Throwable { - // create the SSLServerSocket which will be used by server side + // set up the properties pointing to the key/trust stores + setUpStoreProperties(); + SSLContext ctx = getContext(); - SSLServerSocket ss = (SSLServerSocket) ctx.getServerSocketFactory().createServerSocket(0); - SSLSocketFactory socketFactory = (SSLSocketFactory) ctx.getSocketFactory(); + SSLSocketFactory socketFactory = ctx.getSocketFactory(); // set up the factory as default HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory); // check the result assertSame("Default SSLSocketFactory differs from expected", - socketFactory, HttpsURLConnection.getDefaultSSLSocketFactory()); + socketFactory, HttpsURLConnection.getDefaultSSLSocketFactory()); - // create the HostnameVerifier to check hostname verification - TestHostnameVerifier hnv = new TestHostnameVerifier(); - HttpsURLConnection.setDefaultHostnameVerifier(hnv); + // set the initial default host name verifier. + TestHostnameVerifier initialHostnameVerifier = new TestHostnameVerifier(); + HttpsURLConnection.setDefaultHostnameVerifier(initialHostnameVerifier); + + // create a webserver to check and respond to requests + SingleRequestDispatcher dispatcher = new SingleRequestDispatcher(GET_METHOD, OK_CODE); + MockWebServer webServer = createWebServer(ctx, dispatcher); // create HttpsURLConnection to be tested - URL url = new URL("https://localhost:" + ss.getLocalPort()); + URL url = webServer.getUrl("/"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); - TestHostnameVerifier hnv_late = new TestHostnameVerifier(); - // late initialization: should not be used for created connection - HttpsURLConnection.setDefaultHostnameVerifier(hnv_late); + // late initialization: this HostnameVerifier should not be used for created connection + TestHostnameVerifier lateHostnameVerifier = new TestHostnameVerifier(); + HttpsURLConnection.setDefaultHostnameVerifier(lateHostnameVerifier); // perform the interaction between the peers - SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss); - // check the connection state - checkConnectionStateParameters(connection, peerSocket); + executeClientRequest(connection, false /* doOutput */); + checkConnectionStateParameters(connection, dispatcher.getLastRequest()); + // check the verification process - assertTrue("Hostname verification was not done", hnv.verified); + assertTrue("Hostname verification was not done", initialHostnameVerifier.verified); assertFalse("Hostname verification should not be done by this verifier", - hnv_late.verified); + lateHostnameVerifier.verified); // check the used SSLSocketFactory assertSame("Default SSLSocketFactory should be used", - HttpsURLConnection.getDefaultSSLSocketFactory(), - connection.getSSLSocketFactory()); + HttpsURLConnection.getDefaultSSLSocketFactory(), + connection.getSSLSocketFactory()); - // should silently exit - connection.connect(); + webServer.shutdown(); } /** - * Tests possibility to set up the SSLSocketFactory - * to be used by HttpsURLConnection. + * Tests + * {@link javax.net.ssl.HttpsURLConnection#setSSLSocketFactory(javax.net.ssl.SSLSocketFactory)}. */ public void testSetSSLSocketFactory() throws Throwable { - // create the SSLServerSocket which will be used by server side + // set up the properties pointing to the key/trust stores SSLContext ctx = getContext(); - SSLServerSocket ss = (SSLServerSocket) ctx.getServerSocketFactory().createServerSocket(0); - // create the HostnameVerifier to check hostname verification - TestHostnameVerifier hnv = new TestHostnameVerifier(); - HttpsURLConnection.setDefaultHostnameVerifier(hnv); + // set the initial default host name verifier. + TestHostnameVerifier hostnameVerifier = new TestHostnameVerifier(); + HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); + + // create a webserver to check and respond to requests + SingleRequestDispatcher dispatcher = new SingleRequestDispatcher(GET_METHOD, OK_CODE); + MockWebServer webServer = createWebServer(ctx, dispatcher); // create HttpsURLConnection to be tested - URL url = new URL("https://localhost:" + ss.getLocalPort()); + URL url = webServer.getUrl("/"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); - SSLSocketFactory socketFactory = (SSLSocketFactory) ctx.getSocketFactory(); + // late initialization: should not be used for the created connection. + SSLSocketFactory socketFactory = ctx.getSocketFactory(); connection.setSSLSocketFactory(socketFactory); - TestHostnameVerifier hnv_late = new TestHostnameVerifier(); // late initialization: should not be used for created connection - HttpsURLConnection.setDefaultHostnameVerifier(hnv_late); + TestHostnameVerifier lateHostnameVerifier = new TestHostnameVerifier(); + HttpsURLConnection.setDefaultHostnameVerifier(lateHostnameVerifier); // perform the interaction between the peers - SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss); - // check the connection state - checkConnectionStateParameters(connection, peerSocket); + executeClientRequest(connection, false /* doOutput */); + checkConnectionStateParameters(connection, dispatcher.getLastRequest()); // check the verification process - assertTrue("Hostname verification was not done", hnv.verified); + assertTrue("Hostname verification was not done", hostnameVerifier.verified); assertFalse("Hostname verification should not be done by this verifier", - hnv_late.verified); + lateHostnameVerifier.verified); // check the used SSLSocketFactory assertNotSame("Default SSLSocketFactory should not be used", - HttpsURLConnection.getDefaultSSLSocketFactory(), - connection.getSSLSocketFactory()); - assertSame("Result differs from expected", - socketFactory, connection.getSSLSocketFactory()); + HttpsURLConnection.getDefaultSSLSocketFactory(), + connection.getSSLSocketFactory()); + assertSame("Result differs from expected", socketFactory, connection.getSSLSocketFactory()); - // should silently exit - connection.connect(); + webServer.shutdown(); } /** @@ -304,97 +317,107 @@ public class HttpsURLConnectionTest extends TestCase { * Tests if setHostnameVerifier() method replaces default verifier. */ public void testSetHostnameVerifier() throws Throwable { - // setting up the properties pointing to the key/trust stores + // set up the properties pointing to the key/trust stores setUpStoreProperties(); - // create the SSLServerSocket which will be used by server side - SSLServerSocket ss = (SSLServerSocket) - getContext().getServerSocketFactory().createServerSocket(0); + SSLContext ctx = getContext(); + + TestHostnameVerifier defaultHostnameVerifier = new TestHostnameVerifier(); + HttpsURLConnection.setDefaultHostnameVerifier(defaultHostnameVerifier); - // create the HostnameVerifier to check that Hostname verification - // is done - TestHostnameVerifier hnv = new TestHostnameVerifier(); - HttpsURLConnection.setDefaultHostnameVerifier(hnv); + // create a webserver to check and respond to requests + SingleRequestDispatcher dispatcher = new SingleRequestDispatcher(GET_METHOD, OK_CODE); + MockWebServer webServer = createWebServer(ctx, dispatcher); // create HttpsURLConnection to be tested - URL url = new URL("https://localhost:" + ss.getLocalPort()); + URL url = webServer.getUrl("/"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setSSLSocketFactory(getContext().getSocketFactory()); - TestHostnameVerifier hnv_late = new TestHostnameVerifier(); - // replace default verifier - connection.setHostnameVerifier(hnv_late); + // replace the default verifier + TestHostnameVerifier connectionHostnameVerifier = new TestHostnameVerifier(); + connection.setHostnameVerifier(connectionHostnameVerifier); // perform the interaction between the peers and check the results - SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss); - assertTrue("Hostname verification was not done", hnv_late.verified); + executeClientRequest(connection, false /* doOutput */); + assertTrue("Hostname verification was not done", connectionHostnameVerifier.verified); assertFalse("Hostname verification should not be done by this verifier", - hnv.verified); - checkConnectionStateParameters(connection, peerSocket); + defaultHostnameVerifier.verified); - // should silently exit - connection.connect(); + checkConnectionStateParameters(connection, dispatcher.getLastRequest()); + + webServer.shutdown(); } /** * Tests the behaviour in case of sending the data to the server. */ public void test_doOutput() throws Throwable { - // setting up the properties pointing to the key/trust stores + // set up the properties pointing to the key/trust stores setUpStoreProperties(); - // create the SSLServerSocket which will be used by server side - SSLServerSocket ss = (SSLServerSocket) - getContext().getServerSocketFactory().createServerSocket(0); + SSLContext ctx = getContext(); - // create the HostnameVerifier to check that Hostname verification - // is done - TestHostnameVerifier hnv = new TestHostnameVerifier(); - HttpsURLConnection.setDefaultHostnameVerifier(hnv); + // create a webserver to check and respond to requests + SingleRequestDispatcher dispatcher = new SingleRequestDispatcher(POST_METHOD, OK_CODE); + MockWebServer webServer = createWebServer(ctx, dispatcher); + + // set the HostnameVerifier required to satisfy SSL - always returns "verified". + HttpsURLConnection.setDefaultHostnameVerifier(new TestHostnameVerifier()); // create HttpsURLConnection to be tested - URL url = new URL("https://localhost:" + ss.getLocalPort()); + URL url = webServer.getUrl("/"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setSSLSocketFactory(getContext().getSocketFactory()); - connection.setDoOutput(true); // perform the interaction between the peers and check the results - SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss); - checkConnectionStateParameters(connection, peerSocket); + executeClientRequest(connection, true /* doOutput */); + checkConnectionStateParameters(connection, dispatcher.getLastRequest()); // should silently exit connection.connect(); + + webServer.shutdown(); } /** * Tests HTTPS connection process made through the proxy server. */ public void testProxyConnection() throws Throwable { - // setting up the properties pointing to the key/trust stores + // set up the properties pointing to the key/trust stores setUpStoreProperties(); - // create the SSLServerSocket which will be used by server side - ServerSocket ss = new ServerSocket(0); + SSLContext ctx = getContext(); - // create the HostnameVerifier to check that Hostname verification - // is done - TestHostnameVerifier hnv = new TestHostnameVerifier(); - HttpsURLConnection.setDefaultHostnameVerifier(hnv); + // set the HostnameVerifier required to satisfy SSL - always returns "verified". + HttpsURLConnection.setDefaultHostnameVerifier(new TestHostnameVerifier()); + + // create a server that pretends to be both a proxy and then the webserver + // request 1: proxy CONNECT, respond with OK + ProxyConnectDispatcher proxyConnectDispatcher = + new ProxyConnectDispatcher(false /* authenticationRequired */); + // request 2: tunnelled GET, respond with OK + SingleRequestDispatcher getDispatcher = new SingleRequestDispatcher(GET_METHOD, OK_CODE); + DelegatingDispatcher delegatingDispatcher = + new DelegatingDispatcher(proxyConnectDispatcher, getDispatcher); + MockWebServer proxyAndWebServer = createProxyAndWebServer(ctx, delegatingDispatcher); // create HttpsURLConnection to be tested + URL proxyUrl = proxyAndWebServer.getUrl("/"); + InetSocketAddress proxyAddress = new InetSocketAddress("localhost", proxyUrl.getPort()); URL url = new URL("https://requested.host:55556/requested.data"); HttpsURLConnection connection = (HttpsURLConnection) - url.openConnection(new Proxy(Proxy.Type.HTTP, - new InetSocketAddress("localhost", - ss.getLocalPort()))); + url.openConnection(new Proxy(Proxy.Type.HTTP, proxyAddress)); connection.setSSLSocketFactory(getContext().getSocketFactory()); // perform the interaction between the peers and check the results - SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss); - checkConnectionStateParameters(connection, peerSocket); + executeClientRequest(connection, false /* doOutput */); + checkConnectionStateParameters(connection, getDispatcher.getLastRequest()); // should silently exit connection.connect(); + + proxyAndWebServer.shutdown(); } /** @@ -402,81 +425,105 @@ public class HttpsURLConnectionTest extends TestCase { * Proxy server needs authentication. */ public void testProxyAuthConnection() throws Throwable { - // setting up the properties pointing to the key/trust stores + // set up the properties pointing to the key/trust stores setUpStoreProperties(); - // create the SSLServerSocket which will be used by server side - ServerSocket ss = new ServerSocket(0); + SSLContext ctx = getContext(); - // create the HostnameVerifier to check that Hostname verification - // is done - TestHostnameVerifier hnv = new TestHostnameVerifier(); - HttpsURLConnection.setDefaultHostnameVerifier(hnv); + // set the HostnameVerifier required to satisfy SSL - always returns "verified". + HttpsURLConnection.setDefaultHostnameVerifier(new TestHostnameVerifier()); Authenticator.setDefault(new Authenticator() { - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication("user", "password" - .toCharArray()); + return new PasswordAuthentication("user", "password".toCharArray()); } }); + // create a server that pretends to be both a proxy and then the webserver + // request 1: proxy CONNECT, respond with auth challenge + ProxyConnectAuthFailDispatcher authFailDispatcher = new ProxyConnectAuthFailDispatcher(); + // request 2: proxy CONNECT, respond with OK + ProxyConnectDispatcher proxyConnectDispatcher = + new ProxyConnectDispatcher(true /* authenticationRequired */); + // request 3: tunnelled GET, respond with OK + SingleRequestDispatcher getDispatcher = new SingleRequestDispatcher(GET_METHOD, OK_CODE); + DelegatingDispatcher delegatingDispatcher = new DelegatingDispatcher( + authFailDispatcher, proxyConnectDispatcher, getDispatcher); + MockWebServer proxyAndWebServer = createProxyAndWebServer(ctx, delegatingDispatcher); + // create HttpsURLConnection to be tested + URL proxyUrl = proxyAndWebServer.getUrl("/"); + InetSocketAddress proxyAddress = new InetSocketAddress("localhost", proxyUrl.getPort()); URL url = new URL("https://requested.host:55555/requested.data"); HttpsURLConnection connection = (HttpsURLConnection) - url.openConnection(new Proxy(Proxy.Type.HTTP, - new InetSocketAddress("localhost", - ss.getLocalPort()))); + url.openConnection(new Proxy(Proxy.Type.HTTP, proxyAddress)); connection.setSSLSocketFactory(getContext().getSocketFactory()); // perform the interaction between the peers and check the results - SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss); - checkConnectionStateParameters(connection, peerSocket); + executeClientRequest(connection, false /* doOutput */); + checkConnectionStateParameters(connection, getDispatcher.getLastRequest()); // should silently exit connection.connect(); + + proxyAndWebServer.shutdown(); } /** * Tests HTTPS connection process made through the proxy server. - * 2 HTTPS connections are opened for one URL. For the first time - * the connection is opened through one proxy, - * for the second time through another. + * Two HTTPS connections are opened for one URL: the first time the connection is opened + * through one proxy, the second time it is opened through another. */ public void testConsequentProxyConnection() throws Throwable { - // setting up the properties pointing to the key/trust stores + // set up the properties pointing to the key/trust stores setUpStoreProperties(); - // create the SSLServerSocket which will be used by server side - ServerSocket ss = new ServerSocket(0); + // set the HostnameVerifier required to satisfy SSL - always returns "verified". + HttpsURLConnection.setDefaultHostnameVerifier(new TestHostnameVerifier()); - // create the HostnameVerifier to check that Hostname verification - // is done - TestHostnameVerifier hnv = new TestHostnameVerifier(); - HttpsURLConnection.setDefaultHostnameVerifier(hnv); + // create a server that pretends to be both a proxy and then the webserver + SingleRequestDispatcher getDispatcher1 = new SingleRequestDispatcher(GET_METHOD, OK_CODE); + MockWebServer proxyAndWebServer1 = createProxiedServer(getDispatcher1); // create HttpsURLConnection to be tested + URL proxyUrl1 = proxyAndWebServer1.getUrl("/"); URL url = new URL("https://requested.host:55555/requested.data"); + InetSocketAddress proxyAddress = new InetSocketAddress("localhost", proxyUrl1.getPort()); HttpsURLConnection connection = (HttpsURLConnection) - url.openConnection(new Proxy(Proxy.Type.HTTP, - new InetSocketAddress("localhost", - ss.getLocalPort()))); + url.openConnection(new Proxy(Proxy.Type.HTTP, proxyAddress)); connection.setSSLSocketFactory(getContext().getSocketFactory()); + executeClientRequest(connection, false /* doOutput */); + checkConnectionStateParameters(connection, getDispatcher1.getLastRequest()); - // perform the interaction between the peers and check the results - SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss); - checkConnectionStateParameters(connection, peerSocket); + proxyAndWebServer1.shutdown(); - // create another SSLServerSocket which will be used by server side - ss = new ServerSocket(0); + // create another server + SingleRequestDispatcher getDispatcher2 = new SingleRequestDispatcher(GET_METHOD, OK_CODE); + MockWebServer proxyAndWebServer2 = createProxiedServer(getDispatcher2); - connection = (HttpsURLConnection) url.openConnection(new Proxy( - Proxy.Type.HTTP, new InetSocketAddress("localhost", ss.getLocalPort()))); - connection.setSSLSocketFactory(getContext().getSocketFactory()); + // create another HttpsURLConnection to be tested + URL proxyUrl2 = proxyAndWebServer2.getUrl("/"); + InetSocketAddress proxyAddress2 = new InetSocketAddress("localhost", proxyUrl2.getPort()); + HttpsURLConnection connection2 = (HttpsURLConnection) url.openConnection( + new Proxy(Proxy.Type.HTTP, proxyAddress2)); + connection2.setSSLSocketFactory(getContext().getSocketFactory()); // perform the interaction between the peers and check the results - peerSocket = (SSLSocket) doInteraction(connection, ss); - checkConnectionStateParameters(connection, peerSocket); + executeClientRequest(connection2, false /* doOutput */); + checkConnectionStateParameters(connection2, getDispatcher2.getLastRequest()); + + proxyAndWebServer2.shutdown(); + } + + private static MockWebServer createProxiedServer(Dispatcher getDispatcher) + throws Exception { + // request 1: proxy CONNECT, respond with OK + ProxyConnectDispatcher proxyConnectDispatcher = + new ProxyConnectDispatcher(false /* authenticationRequired */); + // request 2: The get dispatcher. + DelegatingDispatcher delegatingDispatcher1 = + new DelegatingDispatcher(proxyConnectDispatcher, getDispatcher); + return createProxyAndWebServer(getContext(), delegatingDispatcher1); } /** @@ -485,37 +532,47 @@ public class HttpsURLConnectionTest extends TestCase { * Client sends data to the server. */ public void testProxyAuthConnection_doOutput() throws Throwable { - // setting up the properties pointing to the key/trust stores + // set up the properties pointing to the key/trust stores setUpStoreProperties(); - // create the SSLServerSocket which will be used by server side - ServerSocket ss = new ServerSocket(0); + SSLContext ctx = getContext(); - // create the HostnameVerifier to check that Hostname verification - // is done - TestHostnameVerifier hnv = new TestHostnameVerifier(); - HttpsURLConnection.setDefaultHostnameVerifier(hnv); + // set the HostnameVerifier required to satisfy SSL - always returns "verified". + HttpsURLConnection.setDefaultHostnameVerifier(new TestHostnameVerifier()); Authenticator.setDefault(new Authenticator() { - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication("user", "password" - .toCharArray()); + return new PasswordAuthentication("user", "password".toCharArray()); } }); + // create a server that pretends to be both a proxy and then the webserver + // request 1: proxy CONNECT, respond with auth challenge + ProxyConnectAuthFailDispatcher authFailDispatcher = new ProxyConnectAuthFailDispatcher(); + // request 2: proxy CONNECT, respond with OK + ProxyConnectDispatcher proxyConnectDispatcher = + new ProxyConnectDispatcher(true /* authenticationRequired */); + // request 3: tunnelled POST, respond with OK + SingleRequestDispatcher postDispatcher = new SingleRequestDispatcher(POST_METHOD, OK_CODE); + DelegatingDispatcher delegatingDispatcher = new DelegatingDispatcher( + authFailDispatcher, proxyConnectDispatcher, postDispatcher); + MockWebServer proxyAndWebServer = createProxyAndWebServer(ctx, delegatingDispatcher); + URL proxyUrl = proxyAndWebServer.getUrl("/"); + // create HttpsURLConnection to be tested - URL url = new URL("https://requested.host:55554/requested.data"); + InetSocketAddress proxyAddress = new InetSocketAddress("localhost", proxyUrl.getPort()); HttpsURLConnection connection = (HttpsURLConnection) - url.openConnection(new Proxy(Proxy.Type.HTTP, - new InetSocketAddress("localhost", - ss.getLocalPort()))); + proxyUrl.openConnection(new Proxy(Proxy.Type.HTTP, proxyAddress)); connection.setSSLSocketFactory(getContext().getSocketFactory()); - connection.setDoOutput(true); // perform the interaction between the peers and check the results - SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss, OK_CODE, true); - checkConnectionStateParameters(connection, peerSocket); + executeClientRequest(connection, true /* doOutput */); + checkConnectionStateParameters(connection, postDispatcher.getLastRequest()); + + // should silently exit + connection.connect(); + + proxyAndWebServer.shutdown(); } /** @@ -524,79 +581,82 @@ public class HttpsURLConnectionTest extends TestCase { * (Authenticator was not set up in the system). */ public void testProxyAuthConnectionFailed() throws Throwable { - // setting up the properties pointing to the key/trust stores + // set up the properties pointing to the key/trust stores setUpStoreProperties(); - // create the SSLServerSocket which will be used by server side - ServerSocket ss = new ServerSocket(0); + // set the HostnameVerifier required to satisfy SSL - always returns "verified". + HttpsURLConnection.setDefaultHostnameVerifier(new TestHostnameVerifier()); - // create the HostnameVerifier to check that Hostname verification - // is done - TestHostnameVerifier hnv = new TestHostnameVerifier(); - HttpsURLConnection.setDefaultHostnameVerifier(hnv); + // create a server that pretends to be both a proxy that requests authentication. + MockWebServer proxyAndWebServer = new MockWebServer(); + ProxyConnectAuthFailDispatcher authFailDispatcher = new ProxyConnectAuthFailDispatcher(); + proxyAndWebServer.setDispatcher(authFailDispatcher); + proxyAndWebServer.play(); // create HttpsURLConnection to be tested + URL proxyUrl = proxyAndWebServer.getUrl("/"); + InetSocketAddress proxyAddress = new InetSocketAddress("localhost", proxyUrl.getPort()); URL url = new URL("https://requested.host:55555/requested.data"); HttpsURLConnection connection = (HttpsURLConnection) - url.openConnection(new Proxy(Proxy.Type.HTTP, - new InetSocketAddress("localhost", - ss.getLocalPort()))); + url.openConnection(new Proxy(Proxy.Type.HTTP, proxyAddress)); connection.setSSLSocketFactory(getContext().getSocketFactory()); // perform the interaction between the peers and check the results try { - doInteraction(connection, ss, AUTHENTICATION_REQUIRED_CODE, true); + executeClientRequest(connection, false); } catch (IOException e) { // SSL Tunnelling failed if (DO_LOG) { - System.out.println("Got expected IOException: " - + e.getMessage()); + System.out.println("Got expected IOException: " + e.getMessage()); } } } /** - * Tests the behaviour of HTTPS connection in case of unavailability - * of requested resource. + * Tests the behaviour of HTTPS connection in case of unavailability of requested resource (as + * reported by the target web server). */ public void testProxyConnection_Not_Found_Response() throws Throwable { - // setting up the properties pointing to the key/trust stores + // set up the properties pointing to the key/trust stores setUpStoreProperties(); - // create the SSLServerSocket which will be used by server side - ServerSocket ss = new ServerSocket(0); + SSLContext ctx = getContext(); - // create the HostnameVerifier to check that Hostname verification - // is done - TestHostnameVerifier hnv = new TestHostnameVerifier(); - HttpsURLConnection.setDefaultHostnameVerifier(hnv); + // set the HostnameVerifier required to satisfy SSL - always returns "verified". + HttpsURLConnection.setDefaultHostnameVerifier(new TestHostnameVerifier()); + + // create a server that pretends to be a proxy + ProxyConnectDispatcher proxyConnectDispatcher = + new ProxyConnectDispatcher(false /* authenticationRequired */); + SingleRequestDispatcher notFoundDispatcher = + new SingleRequestDispatcher(GET_METHOD, NOT_FOUND_CODE); + DelegatingDispatcher delegatingDispatcher = + new DelegatingDispatcher(proxyConnectDispatcher, notFoundDispatcher); + MockWebServer proxyAndWebServer = createProxyAndWebServer(ctx, delegatingDispatcher); // create HttpsURLConnection to be tested - URL url = new URL("https://localhost:" + ss.getLocalPort()); + URL proxyUrl = proxyAndWebServer.getUrl("/"); + InetSocketAddress proxyAddress = new InetSocketAddress("localhost", proxyUrl.getPort()); + URL url = new URL("https://requested.host:55555/requested.data"); HttpsURLConnection connection = (HttpsURLConnection) - url.openConnection(new Proxy(Proxy.Type.HTTP, - new InetSocketAddress("localhost", - ss.getLocalPort()))); + url.openConnection(new Proxy(Proxy.Type.HTTP, proxyAddress)); connection.setSSLSocketFactory(getContext().getSocketFactory()); try { - doInteraction(connection, ss, NOT_FOUND_CODE); // NOT FOUND + executeClientRequest(connection, false /* doOutput */); fail("Expected exception was not thrown."); } catch (FileNotFoundException e) { if (DO_LOG) { - System.out.println("Expected exception was thrown: " - + e.getMessage()); + System.out.println("Expected exception was thrown: " + e.getMessage()); } } } - /** - * Log the name of the test case to be executed. - */ public void setUp() throws Exception { super.setUp(); if (DO_LOG) { + // Log the name of the test case to be executed. System.out.println(); System.out.println("------------------------"); System.out.println("------ " + getName()); @@ -604,8 +664,8 @@ public class HttpsURLConnectionTest extends TestCase { } if (store != null) { - String ksFileName = ("org/apache/harmony/luni/tests/key_store." - + KeyStore.getDefaultType().toLowerCase()); + String ksFileName = "org/apache/harmony/luni/tests/key_store." + + KeyStore.getDefaultType().toLowerCase(); InputStream in = getClass().getClassLoader().getResourceAsStream(ksFileName); FileOutputStream out = new FileOutputStream(store); BufferedInputStream bufIn = new BufferedInputStream(in, 8192); @@ -627,28 +687,21 @@ public class HttpsURLConnectionTest extends TestCase { } } - /** - * Checks the HttpsURLConnection getter's values and compares - * them with actual corresponding values of remote peer. - */ - public static void checkConnectionStateParameters( - HttpsURLConnection clientConnection, SSLSocket serverPeer) - throws Exception { - SSLSession session = serverPeer.getSession(); - - assertEquals(session.getCipherSuite(), clientConnection.getCipherSuite()); - assertEquals(session.getLocalPrincipal(), clientConnection.getPeerPrincipal()); - assertEquals(session.getPeerPrincipal(), clientConnection.getLocalPrincipal()); + private static void checkConnectionStateParameters( + HttpsURLConnection connection, RecordedRequest request) throws Exception { + assertEquals(request.getSslCipherSuite(), connection.getCipherSuite()); + assertEquals(request.getSslLocalPrincipal(), connection.getPeerPrincipal()); + assertEquals(request.getSslPeerPrincipal(), connection.getLocalPrincipal()); - Certificate[] serverCertificates = clientConnection.getServerCertificates(); - Certificate[] localCertificates = session.getLocalCertificates(); + Certificate[] serverCertificates = connection.getServerCertificates(); + Certificate[] localCertificates = request.getSslLocalCertificates(); assertTrue("Server certificates differ from expected", - Arrays.equals(serverCertificates, localCertificates)); + Arrays.equals(serverCertificates, localCertificates)); - localCertificates = clientConnection.getLocalCertificates(); - serverCertificates = session.getPeerCertificates(); + localCertificates = connection.getLocalCertificates(); + serverCertificates = request.getSslPeerCertificates(); assertTrue("Local certificates differ from expected", - Arrays.equals(serverCertificates, localCertificates)); + Arrays.equals(serverCertificates, localCertificates)); } /** @@ -714,395 +767,233 @@ public class HttpsURLConnectionTest extends TestCase { } /** - * Performs interaction between client's HttpsURLConnection and - * servers side (ServerSocket). + * The host name verifier used in test. */ - public static Socket doInteraction(final HttpsURLConnection clientConnection, - final ServerSocket serverSocket) - throws Throwable { - return doInteraction(clientConnection, serverSocket, OK_CODE, false); + static class TestHostnameVerifier implements HostnameVerifier { + + boolean verified = false; + + public boolean verify(String hostname, SSLSession session) { + if (DO_LOG) { + System.out.println("***> verification " + hostname + " " + + session.getPeerHost()); + } + verified = true; + return true; + } } /** - * Performs interaction between client's HttpsURLConnection and - * servers side (ServerSocket). Server will response with specified - * response code. + * Creates a {@link MockWebServer} that acts as both a proxy and then a web server with the + * supplied {@link SSLContext} and {@link Dispatcher}. The dispatcher provided must handle the + * CONNECT request/responses and {@link SocketPolicy} needed to simulate the hand-off from proxy + * to web server. See {@link HttpsURLConnectionTest.ProxyConnectDispatcher}. */ - public static Socket doInteraction(final HttpsURLConnection clientConnection, - final ServerSocket serverSocket, - final int responseCode) - throws Throwable { - return doInteraction(clientConnection, serverSocket, responseCode, false); + private static MockWebServer createProxyAndWebServer(SSLContext ctx, Dispatcher dispatcher) + throws IOException { + return createServer(ctx, dispatcher, true /* handleProxying */); } /** - * Performs interaction between client's HttpsURLConnection and - * servers side (ServerSocket). Server will response with specified - * response code. - * @param doAuthentication specifies - * if the server needs client authentication. + * Creates a {@link MockWebServer} that acts as (only) a web server with the supplied + * {@link SSLContext} and {@link Dispatcher}. */ - public static Socket doInteraction(final HttpsURLConnection clientConnection, - final ServerSocket serverSocket, - final int responseCode, - final boolean doAuthentication) - throws Throwable { - // set up the connection - clientConnection.setDoInput(true); - clientConnection.setConnectTimeout(TIMEOUT); - clientConnection.setReadTimeout(TIMEOUT); + private static MockWebServer createWebServer(SSLContext ctx, Dispatcher dispatcher) + throws IOException { + return createServer(ctx, dispatcher, false /* handleProxying */); + } - ServerWork server = new ServerWork(serverSocket, responseCode, doAuthentication); + private static MockWebServer createServer( + SSLContext ctx, Dispatcher dispatcher, boolean handleProxying) + throws IOException { + MockWebServer webServer = new MockWebServer(); + webServer.useHttps(ctx.getSocketFactory(), handleProxying /* tunnelProxy */); + webServer.setDispatcher(dispatcher); + webServer.play(); + return webServer; + } - ClientConnectionWork client = new ClientConnectionWork(clientConnection); + /** + * A {@link Dispatcher} that has a list of dispatchers to delegate to, each of which will be + * used for one request and then discarded. + */ + private static class DelegatingDispatcher extends Dispatcher { + private LinkedList<Dispatcher> delegates = new LinkedList<Dispatcher>(); - ExecutorService executorService = Executors.newFixedThreadPool(2); - try { - Future<Void> serverFuture = executorService.submit(server); - Future<Void> clientFuture = executorService.submit(client); - - Throwable t = null; - try { - serverFuture.get(30, TimeUnit.SECONDS); - } catch (ExecutionException e) { - t = e.getCause(); - } - try { - clientFuture.get(30, TimeUnit.SECONDS); - } catch (ExecutionException e) { - // two problems? log the first before overwriting - if (t != null) { - t.printStackTrace(); - } - t = e.getCause(); - } - if (t != null) { - throw t; - } - } catch (ExecutionException e) { - throw e.getCause(); - } finally { - executorService.shutdown(); + public DelegatingDispatcher(Dispatcher... dispatchers) { + addAll(dispatchers); + } + + private void addAll(Dispatcher... dispatchers) { + Collections.addAll(delegates, dispatchers); + } + + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + return delegates.removeFirst().dispatch(request); } - return server.peerSocket; + @Override + public SocketPolicy peekSocketPolicy() { + return delegates.getFirst().peekSocketPolicy(); + } } - /** - * The host name verifier used in test. - */ - static class TestHostnameVerifier implements HostnameVerifier { + /** Handles a request for SSL tunnel: Answers with a request to authenticate. */ + private static class ProxyConnectAuthFailDispatcher extends Dispatcher { - boolean verified = false; + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + assertEquals("CONNECT", request.getMethod()); - public boolean verify(String hostname, SSLSession session) { - if (DO_LOG) { - System.out.println("***> verification " + hostname + " " - + session.getPeerHost()); - } - verified = true; - return true; + MockResponse response = new MockResponse(); + response.setResponseCode(AUTHENTICATION_REQUIRED_CODE); + response.addHeader("Proxy-authenticate: Basic realm=\"localhost\""); + log("Authentication required. Sending response: " + response); + return response; + } + + private void log(String msg) { + HttpsURLConnectionTest.log("ProxyConnectAuthFailDispatcher", msg); } } /** - * The base class for mock Client and Server. + * Handles a request for SSL tunnel: Answers with a success and the socket is upgraded to SSL. */ - static class Work { - - /** - * The header of OK HTTP response. - */ - static final String responseHead = "HTTP/1.1 200 OK\r\n"; - - /** - * The response message to be sent to the proxy CONNECT request. - */ - static final String proxyResponse = responseHead + "\r\n"; - - /** - * The content of the response to be sent during HTTPS session. - */ - static final String httpsResponseContent - = "<HTML>\n" - + "<HEAD><TITLE>HTTPS Response Content</TITLE></HEAD>\n" - + "</HTML>"; - - /** - * The tail of the response to be sent during HTTPS session. - */ - static final String httpsResponseTail - = "Content-type: text/html\r\n" - + "Content-length: " + httpsResponseContent.length() + "\r\n" - + "\r\n" - + httpsResponseContent; - - /** - * The response requiring client's proxy authentication. - */ - static final String respAuthenticationRequired - = "HTTP/1.0 407 Proxy authentication required\r\n" - + "Proxy-authenticate: Basic realm=\"localhost\"\r\n" - + "\r\n"; - - /** - * The data to be posted by client to the server. - */ - static final String clientsData = "_.-^ Client's Data ^-._"; - - /** - * The print stream used for debug log. - * If it is null debug info will not be printed. - */ - private PrintStream out = System.out; - - /** - * Prints log message. - */ - public synchronized void log(String message) { - if (DO_LOG && (out != null)) { - out.println("[" + this + "]: " + message); + private static class ProxyConnectDispatcher extends Dispatcher { + + private final boolean authenticationRequired; + + private ProxyConnectDispatcher(boolean authenticationRequired) { + this.authenticationRequired = authenticationRequired; + } + + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + if (authenticationRequired) { + // check provided authorization credentials + assertNotNull("no proxy-authorization credentials: " + request, + request.getHeader("proxy-authorization")); + log("Got authenticated request:\n" + request); + log("------------------"); } + + assertEquals("CONNECT", request.getMethod()); + log("Send proxy response"); + MockResponse response = new MockResponse(); + response.setResponseCode(200); + response.setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END); + return response; + } + + @Override + public SocketPolicy peekSocketPolicy() { + return SocketPolicy.UPGRADE_TO_SSL_AT_END; + } + + private void log(String msg) { + HttpsURLConnectionTest.log("ProxyConnectDispatcher", msg); } } /** - * The class used for server side works. + * Handles a request: Answers with a response with a specified status code. + * If the {@code expectedMethod} is {@code POST} a hardcoded response body {@link #POST_DATA} + * will be included in the response. */ - static class ServerWork extends Work implements Callable<Void> { - - // the server socket used for connection - private final ServerSocket serverSocket; + private static class SingleRequestDispatcher extends Dispatcher { - // indicates if the server acts as proxy server - private final boolean actAsProxy; - - // indicates if the server needs proxy authentication - private final boolean needProxyAuthentication; - - // response code to be send to the client peer + private final String expectedMethod; private final int responseCode; - // the socket connected with client peer - private Socket peerSocket; - - /** - * Creates the thread acting as a server side. - * @param serverSocket the server socket to be used during connection - * @param responseCode the response code to be sent to the client - * @param needProxyAuthentication - * indicates if the server needs proxy authentication - */ - public ServerWork(ServerSocket serverSocket, - int responseCode, - boolean needProxyAuthentication) { - this.serverSocket = serverSocket; + private RecordedRequest lastRequest; + + private SingleRequestDispatcher(String expectedMethod, int responseCode) { this.responseCode = responseCode; - this.needProxyAuthentication = needProxyAuthentication; - // will act as a proxy server if the specified server socket - // is not a secure server socket - this.actAsProxy = !(serverSocket instanceof SSLServerSocket); - if (!actAsProxy) { - // demand client to send its certificate - ((SSLServerSocket) serverSocket).setNeedClientAuth(true); - } + this.expectedMethod = expectedMethod; } - /** - * Closes the connection. - */ - public void closeSocket(Socket socket) { - if (socket == null) { - return; + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + if (lastRequest != null) { + fail("More than one request received"); } - try { - socket.getInputStream().close(); - } catch (IOException e) {} - try { - socket.getOutputStream().close(); - } catch (IOException e) {} - try { - socket.close(); - } catch (IOException e) {} + log("Request received: " + request); + lastRequest = request; + assertEquals(expectedMethod, request.getMethod()); + if (POST_METHOD.equals(expectedMethod)) { + assertEquals(POST_DATA, request.getUtf8Body()); + } + + MockResponse response = new MockResponse(); + response.setResponseCode(responseCode); + response.setBody(RESPONSE_CONTENT); + + log("Responding with: " + response); + return response; } - /** - * Performs the actual server work. - * If some exception occurs during the work it will be - * stored in the <code>thrown</code> field. - */ - public Void call() throws Exception { - // the buffer used for reading the messages - byte[] buff = new byte[2048]; - // the number of bytes read into the buffer - try { - // configure the server socket to avoid blocking - serverSocket.setSoTimeout(TIMEOUT); - // accept client connection - peerSocket = serverSocket.accept(); - // configure the client connection to avoid blocking - peerSocket.setSoTimeout(TIMEOUT); - log("Client connection ACCEPTED"); - - InputStream is = peerSocket.getInputStream(); - OutputStream os = peerSocket.getOutputStream(); - - int num = is.read(buff); - if (num == -1) { - log("Unexpected EOF"); - return null; - } - - String message = new String(buff, 0, num); - log("Got request:\n" + message); - log("------------------"); + public RecordedRequest getLastRequest() { + return lastRequest; + } - if (!actAsProxy) { - // Act as Server (not Proxy) side - if (message.startsWith("POST")) { - // client connection sent some data - log("try to read client data"); - String data = message.substring(message.indexOf("\r\n\r\n")+4); - log("client's data: '" + data + "'"); - // check the received data - assertEquals(clientsData, data); - } - } else { - if (needProxyAuthentication) { - // Do proxy work - log("Authentication required..."); - // send Authentication Request - os.write(respAuthenticationRequired.getBytes()); - // read request - num = is.read(buff); - if (num == -1) { - // this connection was closed, - // do clean up and create new one: - closeSocket(peerSocket); - peerSocket = serverSocket.accept(); - peerSocket.setSoTimeout(TIMEOUT); - log("New client connection ACCEPTED"); - is = peerSocket.getInputStream(); - os = peerSocket.getOutputStream(); - num = is.read(buff); - } - message = new String(buff, 0, num); - log("Got authenticated request:\n" + message); - log("------------------"); - // check provided authorization credentials - assertTrue("no proxy-authorization credentials: " + message, - message.toLowerCase().indexOf("proxy-authorization:") != -1); - } - - assertTrue(message.startsWith("CONNECT")); - // request for SSL tunnel - log("Send proxy response"); - os.write(proxyResponse.getBytes()); - - log("Perform SSL Handshake..."); - // create sslSocket acting as a remote server peer - SSLSocket sslSocket = (SSLSocket) - getContext().getSocketFactory().createSocket(peerSocket, - "localhost", - peerSocket.getPort(), - true); // do autoclose - sslSocket.setUseClientMode(false); - // demand client authentication - sslSocket.setNeedClientAuth(true); - sslSocket.startHandshake(); - peerSocket = sslSocket; - is = peerSocket.getInputStream(); - os = peerSocket.getOutputStream(); - - // read the HTTP request sent by secure connection - // (HTTPS request) - num = is.read(buff); - message = new String(buff, 0, num); - log("[Remote Server] Request from SSL tunnel:\n" + message); - log("------------------"); - - if (message.startsWith("POST")) { - // client connection sent some data - log("[Remote Server] try to read client data"); - String data = message.substring(message.indexOf("\r\n\r\n")+4); - log("[Remote Server] client's data: '" + message + "'"); - // check the received data - assertEquals(clientsData, data); - } - - log("[Remote Server] Sending the response by SSL tunnel..."); - } - - // send the response with specified response code - os.write(("HTTP/1.1 " + responseCode - + " Message\r\n" + httpsResponseTail).getBytes()); - os.flush(); - os.close(); - log("Work is DONE actAsProxy=" + actAsProxy); - return null; - } finally { - closeSocket(peerSocket); - try { - serverSocket.close(); - } catch (IOException e) {} - } + @Override + public SocketPolicy peekSocketPolicy() { + return SocketPolicy.DISCONNECT_AT_END; } - @Override public String toString() { - return actAsProxy ? "Proxy Server" : "Server"; + private void log(String msg) { + HttpsURLConnectionTest.log("SingleRequestDispatcher", msg); } } /** - * The class used for client side work. + * Executes an HTTP request using the supplied connection. If {@code doOutput} is {@code true} + * the request made is a POST and the request body sent is {@link #POST_DATA}. + * If {@code doOutput} is {@code false} the request made is a GET. The response must be a + * success with a body {@link #RESPONSE_CONTENT}. */ - static class ClientConnectionWork extends Work implements Callable<Void> { - - // connection to be used to contact the server side - private HttpsURLConnection connection; - - /** - * Creates the thread acting as a client side. - * @param connection connection to be used to contact the server side - */ - public ClientConnectionWork(HttpsURLConnection connection) { - this.connection = connection; - log("Created over connection: " + connection.getClass()); - } + private static void executeClientRequest( + HttpsURLConnection connection, boolean doOutput) throws IOException { - /** - * Performs the actual client work. - * If some exception occurs during the work it will be - * stored in the <code>thrown<code> field. - */ - public Void call() throws Exception { - log("Opening the connection to " + connection.getURL()); - connection.connect(); - log("Connection has been ESTABLISHED, using proxy: " + connection.usingProxy()); - if (connection.getDoOutput()) { - log("Posting data"); - // connection configured to post data, do so - connection.getOutputStream().write(clientsData.getBytes()); - } - // read the content of HTTP(s) response - InputStream is = connection.getInputStream(); - log("Input Stream obtained"); - byte[] buff = new byte[2048]; - int num = 0; - int byt = 0; - while ((num < buff.length) && ((byt = is.read()) != -1)) { - buff[num++] = (byte) byt; - } - String message = new String(buff, 0, num); - log("Got content:\n" + message); - log("------------------"); - log("Response code: " + connection.getResponseCode()); - assertEquals(httpsResponseContent, message); - return null; + // set up the connection + connection.setDoInput(true); + connection.setConnectTimeout(TIMEOUT); + connection.setReadTimeout(TIMEOUT); + connection.setDoOutput(doOutput); + + log("Client", "Opening the connection to " + connection.getURL()); + connection.connect(); + log("Client", "Connection has been ESTABLISHED, using proxy: " + connection.usingProxy()); + if (doOutput) { + log("Client", "Posting data"); + // connection configured to post data, do so + OutputStream os = connection.getOutputStream(); + os.write(POST_DATA.getBytes()); + } + // read the content of HTTP(s) response + InputStream is = connection.getInputStream(); + log("Client", "Input Stream obtained"); + byte[] buff = new byte[2048]; + int num = 0; + int byt; + while ((num < buff.length) && ((byt = is.read()) != -1)) { + buff[num++] = (byte) byt; } + String message = new String(buff, 0, num); + log("Client", "Got content:\n" + message); + log("Client", "------------------"); + log("Client", "Response code: " + connection.getResponseCode()); + assertEquals(RESPONSE_CONTENT, message); + } - @Override public String toString() { - return "Client Connection"; + /** + * Prints log message. + */ + public static synchronized void log(String origin, String message) { + if (DO_LOG) { + System.out.println("[" + origin + "]: " + message); } } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectInputStreamTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectInputStreamTest.java index 12406f3..d1f92ec 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectInputStreamTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectInputStreamTest.java @@ -17,13 +17,17 @@ package org.apache.harmony.luni.tests.java.io; +import junit.framework.TestCase; +import org.apache.harmony.testframework.serialization.SerializationTest; +import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; +import tests.support.Support_ASimpleInputStream; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.EOFException; import java.io.Externalizable; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; @@ -35,34 +39,22 @@ import java.io.ObjectInputValidation; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.ObjectStreamClass; +import java.io.ObjectStreamException; import java.io.OutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.Serializable; -import java.io.SerializablePermission; import java.io.StreamCorruptedException; import java.lang.reflect.Proxy; -import java.security.Permission; import java.util.Arrays; import java.util.HashMap; import java.util.Hashtable; import java.util.Vector; -import junit.framework.TestCase; - -import org.apache.harmony.testframework.serialization.SerializationTest; -import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; - @SuppressWarnings("serial") public class ObjectInputStreamTest extends TestCase implements Serializable { - ObjectInputStream ois; - - ObjectOutputStream oos; - - ByteArrayOutputStream bao; - public class SerializableTestHelper implements Serializable { public String aField1; @@ -127,9 +119,306 @@ public class ObjectInputStreamTest extends TestCase implements Hashtable h = new Hashtable(); } - /** - * java.io.ObjectInputStream#readObject() - */ + static final long serialVersionUID = 1L; + + ObjectInputStream ois; + + ObjectOutputStream oos; + + ByteArrayOutputStream bao; + + boolean readStreamHeaderCalled; + + private final String testString = "Lorem ipsum..."; + + private final int testLength = testString.length(); + + public void test_ConstructorLjava_io_InputStream_IOException() throws IOException { + oos.writeObject(testString); + oos.close(); + + Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray()); + sis.throwExceptionOnNextUse = true; + try { + ois = new ObjectInputStream(sis); + fail("Test 1: IOException expected."); + } catch (IOException e) { + // Expected. + } + sis.throwExceptionOnNextUse = false; + } + + public void test_ClassDescriptor() throws IOException, + ClassNotFoundException { + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStreamWithWriteDesc oos = new ObjectOutputStreamWithWriteDesc( + baos); + oos.writeObject(String.class); + oos.close(); + Class<?> cls = TestClassForSerialization.class; + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + ObjectInputStreamWithReadDesc ois = new ObjectInputStreamWithReadDesc( + bais, cls); + Object obj = ois.readObject(); + ois.close(); + assertEquals(cls, obj); + } + + public void test_available_IOException() throws IOException { + oos.writeObject(testString); + oos.close(); + + Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray()); + ois = new ObjectInputStream(sis); + sis.throwExceptionOnNextUse = true; + try { + ois.available(); + fail("Test 1: IOException expected."); + } catch (IOException e) { + // Expected. + } + sis.throwExceptionOnNextUse = false; + ois.close(); + } + + public void test_close() throws Exception { + // Test for method void java.io.ObjectInputStream.close() + oos.writeObject(testString); + oos.close(); + + Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray()); + ois = new ObjectInputStream(sis); + sis.throwExceptionOnNextUse = true; + try { + ois.close(); + fail("Test 1: IOException expected."); + } catch (IOException e) { + // Expected. + } + sis.throwExceptionOnNextUse = false; + ois.close(); + } + + public void test_enableResolveObjectB() throws IOException { + // Start testing without a SecurityManager. + BasicObjectInputStream bois = new BasicObjectInputStream(); + assertFalse("Test 1: Object resolving must be disabled by default.", + bois.enableResolveObject(true)); + + assertTrue("Test 2: enableResolveObject did not return the previous value.", + bois.enableResolveObject(false)); + } + + public void test_read_IOException() throws IOException { + oos.writeObject(testString); + oos.close(); + + Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray()); + ois = new ObjectInputStream(sis); + sis.throwExceptionOnNextUse = true; + try { + ois.read(); + fail("Test 1: IOException expected."); + } catch (IOException e) { + // Expected. + } + sis.throwExceptionOnNextUse = false; + ois.close(); + } + + public void test_read$BII_Exception() throws IOException { + byte[] buf = new byte[testLength]; + oos.writeObject(testString); + oos.close(); + + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + try { + ois.read(buf, 0, -1); + fail("IndexOutOfBoundsException was not thrown."); + } catch (IndexOutOfBoundsException e) { + // Expected + } + try { + ois.read(buf, -1,1); + fail("IndexOutOfBoundsException was not thrown."); + } catch (IndexOutOfBoundsException e) { + // Expected + } + try { + ois.read(buf, testLength, 1); + fail("IndexOutOfBoundsException was not thrown."); + } catch (IndexOutOfBoundsException e) { + // Expected + } + ois.close(); + + + Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray()); + ois = new ObjectInputStream(sis); + sis.throwExceptionOnNextUse = true; + try { + ois.read(buf, 0, testLength); + fail("Test 1: IOException expected."); + } catch (IOException e) { + // Expected. + } + sis.throwExceptionOnNextUse = false; + ois.close(); + } + + public void test_readFully$B() throws IOException { + byte[] buf = new byte[testLength]; + oos.writeBytes(testString); + oos.close(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + ois.readFully(buf); + assertEquals("Test 1: Incorrect bytes read;", + testString, new String(buf)); + ois.close(); + + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + ois.read(); + try { + ois.readFully(buf); + fail("Test 2: EOFException expected."); + } catch (EOFException e) { + // Expected. + } + } + + public void test_readFully$B_Exception() throws IOException { + byte[] buf = new byte[testLength]; + oos.writeObject(testString); + oos.close(); + + Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray()); + ois = new ObjectInputStream(sis); + sis.throwExceptionOnNextUse = true; + try { + ois.readFully(buf); + fail("Test 1: IOException expected."); + } catch (IOException e) { + // Expected. + } + sis.throwExceptionOnNextUse = false; + ois.close(); + } + + public void test_readFully$BII() throws IOException { + // Test for method void java.io.ObjectInputStream.readFully(byte [], + // int, int) + byte[] buf = new byte[testLength]; + oos.writeBytes(testString); + oos.close(); + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + ois.readFully(buf, 0, testLength); + assertEquals("Read incorrect bytes", testString, new String(buf)); + ois.close(); + + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + ois.read(); + try { + ois.readFully(buf); + fail("Test 2: EOFException expected."); + } catch (EOFException e) { + // Expected. + } + } + + public void test_readFully$BII_Exception() throws IOException { + byte[] buf = new byte[testLength]; + oos.writeObject(testString); + oos.close(); + + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + try { + ois.readFully(buf, 0, -1); + fail("IndexOutOfBoundsException was not thrown."); + } catch (IndexOutOfBoundsException e) { + // Expected + } + try { + ois.readFully(buf, -1,1); + fail("IndexOutOfBoundsException was not thrown."); + } catch (IndexOutOfBoundsException e) { + // Expected + } + try { + ois.readFully(buf, testLength, 1); + fail("IndexOutOfBoundsException was not thrown."); + } catch (IndexOutOfBoundsException e) { + // Expected + } + ois.close(); + + Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray()); + ois = new ObjectInputStream(sis); + sis.throwExceptionOnNextUse = true; + try { + ois.readFully(buf, 0, 1); + fail("Test 1: IOException expected."); + } catch (IOException e) { + // Expected. + } + sis.throwExceptionOnNextUse = false; + ois.close(); + } + + public void test_readLine_IOException() throws IOException { + oos.writeObject(testString); + oos.close(); + + Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray()); + ois = new ObjectInputStream(sis); + sis.throwExceptionOnNextUse = true; + try { + ois.readLine(); + fail("Test 1: IOException expected."); + } catch (IOException e) { + // Expected. + } + sis.throwExceptionOnNextUse = false; + ois.close(); + } + + private void fillStreamHeader(byte[] buffer) { + short magic = java.io.ObjectStreamConstants.STREAM_MAGIC; + short version = java.io.ObjectStreamConstants.STREAM_VERSION; + + if (buffer.length < 4) { + throw new IllegalArgumentException("The buffer's minimal length must be 4."); + } + + // Initialize the buffer with the correct header for object streams + buffer[0] = (byte) (magic >> 8); + buffer[1] = (byte) magic; + buffer[2] = (byte) (version >> 8); + buffer[3] = (byte) (version); + } + + public void test_readObjectOverride() throws Exception { + byte[] buffer = new byte[4]; + + // Initialize the buffer with the correct header for object streams + fillStreamHeader(buffer); + + // Test 1: Check that readObjectOverride() returns null if there + // is no input stream. + BasicObjectInputStream bois = new BasicObjectInputStream(); + assertNull("Test 1:", bois.readObjectOverride()); + + // Test 2: Check that readObjectOverride() throws an IOException + // if there is an input stream. + bois = new BasicObjectInputStream(new ByteArrayInputStream(buffer)); + try { + bois.readObjectOverride(); + fail("Test 2: IOException expected."); + } catch (IOException e) {} + + bois.close(); + } + public void test_readObjectMissingClasses() throws Exception { SerializationTest.verifySelf(new A1(), new SerializableAssert() { public void assertDeserialized(Serializable initial, @@ -139,9 +428,190 @@ public class ObjectInputStreamTest extends TestCase implements }); } - /** - * java.io.ObjectInputStream#ObjectInputStream(java.io.InputStream) - */ + public void test_readStreamHeader() throws IOException { + String testString = "Lorem ipsum"; + BasicObjectInputStream bois; + short magic = java.io.ObjectStreamConstants.STREAM_MAGIC; + short version = java.io.ObjectStreamConstants.STREAM_VERSION; + byte[] buffer = new byte[20]; + + // Initialize the buffer with the correct header for object streams + fillStreamHeader(buffer); + System.arraycopy(testString.getBytes(), 0, buffer, 4, testString.length()); + + // Test 1: readStreamHeader should not throw a StreamCorruptedException. + // It should get called by the ObjectInputStream constructor. + try { + readStreamHeaderCalled = false; + bois = new BasicObjectInputStream(new ByteArrayInputStream(buffer)); + bois.close(); + } catch (StreamCorruptedException e) { + fail("Test 1: Unexpected StreamCorruptedException."); + } + assertTrue("Test 1: readStreamHeader() has not been called.", + readStreamHeaderCalled); + + // Test 2: Make the stream magic number invalid and check that + // readStreamHeader() throws an exception. + buffer[0] = (byte)magic; + buffer[1] = (byte)(magic >> 8); + try { + readStreamHeaderCalled = false; + bois = new BasicObjectInputStream(new ByteArrayInputStream(buffer)); + fail("Test 2: StreamCorruptedException expected."); + bois.close(); + } catch (StreamCorruptedException e) { + } + assertTrue("Test 2: readStreamHeader() has not been called.", + readStreamHeaderCalled); + + // Test 3: Make the stream version invalid and check that + // readStreamHeader() throws an exception. + buffer[0] = (byte)(magic >> 8); + buffer[1] = (byte)magic; + buffer[2] = (byte)(version); + buffer[3] = (byte)(version >> 8); + try { + readStreamHeaderCalled = false; + bois = new BasicObjectInputStream(new ByteArrayInputStream(buffer)); + fail("Test 3: StreamCorruptedException expected."); + bois.close(); + } catch (StreamCorruptedException e) { + } + assertTrue("Test 3: readStreamHeader() has not been called.", + readStreamHeaderCalled); + } + + public void test_readUnsignedByte() throws IOException { + oos.writeByte(-1); + oos.close(); + + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + assertEquals("Test 1: Incorrect unsigned byte written or read.", + 255, ois.readUnsignedByte()); + + try { + ois.readUnsignedByte(); + fail("Test 2: EOFException expected."); + } catch (EOFException e) { + // Expected. + } + + ois.close(); + try { + ois.readUnsignedByte(); + fail("Test 3: IOException expected."); + } catch (IOException e) { + // Expected. + } + } + + public void test_readUnsignedShort() throws IOException { + // Test for method int java.io.ObjectInputStream.readUnsignedShort() + oos.writeShort(-1); + oos.close(); + + ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); + assertEquals("Test 1: Incorrect unsigned short written or read.", + 65535, ois.readUnsignedShort()); + + try { + ois.readUnsignedShort(); + fail("Test 2: EOFException expected."); + } catch (EOFException e) { + // Expected. + } + + ois.close(); + try { + ois.readUnsignedShort(); + fail("Test 3: IOException expected."); + } catch (IOException e) { + // Expected. + } + } + + public void test_skipBytesI_IOException() throws IOException { + oos.writeObject(testString); + oos.close(); + + Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray()); + ois = new ObjectInputStream(sis); + sis.throwExceptionOnNextUse = true; + try { + ois.skipBytes(5); + fail("Test 1: IOException expected."); + } catch (IOException e) { + // Expected. + } + sis.throwExceptionOnNextUse = false; + ois.close(); + } + + public static class A implements Serializable { + + private static final long serialVersionUID = 11L; + + public String name = "name"; + } + + public static class B extends A {} + + public static class C extends B { + + private static final long serialVersionUID = 33L; + } + + class BasicObjectInputStream extends ObjectInputStream { + public BasicObjectInputStream() throws IOException, SecurityException { + super(); + } + + public BasicObjectInputStream(InputStream input) throws IOException { + super(input); + } + + public boolean enableResolveObject(boolean enable) + throws SecurityException { + return super.enableResolveObject(enable); + } + + public Object readObjectOverride() throws ClassNotFoundException, IOException { + return super.readObjectOverride(); + } + + public void readStreamHeader() throws IOException { + readStreamHeaderCalled = true; + super.readStreamHeader(); + } + + public Class<?> resolveProxyClass(String[] interfaceNames) + throws IOException, ClassNotFoundException { + return super.resolveProxyClass(interfaceNames); + } + } + + public static class ObjectInputStreamWithReadDesc extends + ObjectInputStream { + private Class returnClass; + + public ObjectInputStreamWithReadDesc(InputStream is, Class returnClass) + throws IOException { + super(is); + this.returnClass = returnClass; + } + + public ObjectStreamClass readClassDescriptor() throws IOException, + ClassNotFoundException { + return ObjectStreamClass.lookup(returnClass); + + } + } + + static class TestClassForSerialization implements Serializable { + private static final long serialVersionUID = 1L; + } + public void test_ConstructorLjava_io_InputStream() throws IOException { oos.writeDouble(Double.MAX_VALUE); oos.close(); @@ -207,9 +677,6 @@ public class ObjectInputStreamTest extends TestCase implements } - /** - * java.io.ObjectInputStream#available() - */ public void test_available() throws IOException { oos.writeBytes("HelloWorld"); oos.close(); @@ -219,16 +686,6 @@ public class ObjectInputStreamTest extends TestCase implements } /** - * java.io.ObjectInputStream#close() - */ - public void test_close() throws IOException { - oos.writeBytes("HelloWorld"); - oos.close(); - ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); - ois.close(); - } - - /** * java.io.ObjectInputStream#defaultReadObject() */ public void test_defaultReadObject() throws Exception { @@ -356,34 +813,6 @@ public class ObjectInputStreamTest extends TestCase implements } /** - * java.io.ObjectInputStream#readFully(byte[]) - */ - public void test_readFully$B() throws IOException { - byte[] buf = new byte[10]; - oos.writeBytes("HelloWorld"); - oos.close(); - ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); - ois.readFully(buf); - ois.close(); - assertEquals("Read incorrect bytes", "HelloWorld", new String(buf, 0, - 10, "UTF-8")); - } - - /** - * java.io.ObjectInputStream#readFully(byte[], int, int) - */ - public void test_readFully$BII() throws IOException { - byte[] buf = new byte[10]; - oos.writeBytes("HelloWorld"); - oos.close(); - ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); - ois.readFully(buf, 0, 10); - ois.close(); - assertEquals("Read incorrect bytes", "HelloWorld", new String(buf, 0, - 10, "UTF-8")); - } - - /** * java.io.ObjectInputStream#readInt() */ public void test_readInt() throws IOException { @@ -510,36 +939,6 @@ public class ObjectInputStreamTest extends TestCase implements } /** - * java.io.ObjectInputStream#readObjectOverride() - */ - public void test_readObjectOverride() throws Exception { - // Regression for HARMONY-846 - assertNull(new ObjectInputStream() { - - @Override - public Object readObjectOverride() throws IOException, - ClassNotFoundException { - return super.readObjectOverride(); - } - - }.readObjectOverride()); - } - - public static class A implements Serializable { - - private static final long serialVersionUID = 11L; - - public String name = "name"; - } - - public static class B extends A {} - - public static class C extends B { - - private static final long serialVersionUID = 33L; - } - - /** * java.io.ObjectInputStream#readObject() */ public void test_readObjectCorrupt() throws IOException, ClassNotFoundException { @@ -568,30 +967,6 @@ public class ObjectInputStreamTest extends TestCase implements } /** - * java.io.ObjectInputStream#readUnsignedByte() - */ - public void test_readUnsignedByte() throws IOException { - oos.writeByte(-1); - oos.close(); - ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); - assertEquals("Read incorrect unsignedByte value", 255, ois - .readUnsignedByte()); - ois.close(); - } - - /** - * java.io.ObjectInputStream#readUnsignedShort() - */ - public void test_readUnsignedShort() throws IOException { - oos.writeShort(-1); - oos.close(); - ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); - assertEquals("Read incorrect unsignedShort value", 65535, ois - .readUnsignedShort()); - ois.close(); - } - - /** * java.io.ObjectInputStream#readUTF() */ public void test_readUTF() throws IOException { @@ -617,26 +992,27 @@ public class ObjectInputStreamTest extends TestCase implements // Regression for HARMONY-844 try { - new ObjectInputStream() {}.skipBytes(0); + new ObjectInputStream() { + }.skipBytes(0); fail("NullPointerException expected"); - } catch (NullPointerException e) {} + } catch (NullPointerException e) { + } } // Regression Test for JIRA 2192 - public void test_readObject_withPrimitiveClass() throws Exception { - File file = new File("test.ser"); - file.deleteOnExit(); - Test test = new Test(); - ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream( - file)); - out.writeObject(test); - out.close(); - - ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); - Test another = (Test) in.readObject(); - in.close(); - assertEquals(test, another); - } + public void test_readObject_withPrimitiveClass() throws Exception { + File file = File.createTempFile("ObjectInputStreamTest", ".ser"); + Test test = new Test(); + ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream( + file)); + out.writeObject(test); + out.close(); + + ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); + Test another = (Test) in.readObject(); + in.close(); + assertEquals(test, another); + } //Regression Test for JIRA-2249 public static class ObjectOutputStreamWithWriteDesc extends @@ -652,75 +1028,36 @@ public class ObjectInputStreamTest extends TestCase implements } } - public static class ObjectIutputStreamWithReadDesc extends + // Regression Test for JIRA-2340 + public static class ObjectOutputStreamWithWriteDesc1 extends + ObjectOutputStream { + public ObjectOutputStreamWithWriteDesc1(OutputStream os) + throws IOException { + super(os); + } + + @Override + public void writeClassDescriptor(ObjectStreamClass desc) + throws IOException { + super.writeClassDescriptor(desc); + } + } + + public static class ObjectInputStreamWithReadDesc1 extends ObjectInputStream { - private Class returnClass; - public ObjectIutputStreamWithReadDesc(InputStream is, Class returnClass) + public ObjectInputStreamWithReadDesc1(InputStream is) throws IOException { super(is); - this.returnClass = returnClass; } @Override public ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException { - return ObjectStreamClass.lookup(returnClass); - + return super.readClassDescriptor(); } } - static class TestClassForSerialization implements Serializable { - private static final long serialVersionUID = 1L; - } - - public void test_ClassDescriptor() throws IOException, - ClassNotFoundException { - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStreamWithWriteDesc oos = new ObjectOutputStreamWithWriteDesc( - baos); - oos.writeObject(String.class); - oos.close(); - Class cls = TestClassForSerialization.class; - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - ObjectIutputStreamWithReadDesc ois = new ObjectIutputStreamWithReadDesc( - bais, cls); - Object obj = ois.readObject(); - ois.close(); - assertEquals(cls, obj); - } - - // Regression Test for JIRA-2340 - public static class ObjectOutputStreamWithWriteDesc1 extends - ObjectOutputStream { - public ObjectOutputStreamWithWriteDesc1(OutputStream os) - throws IOException { - super(os); - } - - @Override - public void writeClassDescriptor(ObjectStreamClass desc) - throws IOException { - super.writeClassDescriptor(desc); - } - } - - public static class ObjectIutputStreamWithReadDesc1 extends - ObjectInputStream { - - public ObjectIutputStreamWithReadDesc1(InputStream is) - throws IOException { - super(is); - } - - @Override - public ObjectStreamClass readClassDescriptor() throws IOException, - ClassNotFoundException { - return super.readClassDescriptor(); - } - } - // Regression test for Harmony-1921 public static class ObjectInputStreamWithResolve extends ObjectInputStream { public ObjectInputStreamWithResolve(InputStream in) throws IOException { @@ -769,7 +1106,7 @@ public class ObjectInputStreamTest extends TestCase implements @Override protected Object resolveObject(Object obj) throws IOException { - if(obj instanceof Integer){ + if (obj instanceof Integer) { obj = intObj; } return super.resolveObject(obj); @@ -792,7 +1129,7 @@ public class ObjectInputStreamTest extends TestCase implements byte[] bytes = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStreamWithResolveObject ois = - new ObjectInputStreamWithResolveObject(bais); + new ObjectInputStreamWithResolveObject(bais); Integer actual = (Integer) ois.readObject(); ois.close(); @@ -800,30 +1137,30 @@ public class ObjectInputStreamTest extends TestCase implements assertEquals(ObjectInputStreamWithResolveObject.intObj, actual); } - public void test_readClassDescriptor() throws IOException, - ClassNotFoundException { + public void test_readClassDescriptor() throws IOException, + ClassNotFoundException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStreamWithWriteDesc1 oos = new ObjectOutputStreamWithWriteDesc1( - baos); - ObjectStreamClass desc = ObjectStreamClass - .lookup(TestClassForSerialization.class); - oos.writeClassDescriptor(desc); - oos.close(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStreamWithWriteDesc1 oos = new ObjectOutputStreamWithWriteDesc1( + baos); + ObjectStreamClass desc = ObjectStreamClass + .lookup(TestClassForSerialization.class); + oos.writeClassDescriptor(desc); + oos.close(); byte[] bytes = baos.toByteArray(); - ByteArrayInputStream bais = new ByteArrayInputStream(bytes); - ObjectIutputStreamWithReadDesc1 ois = new ObjectIutputStreamWithReadDesc1( - bais); - Object obj = ois.readClassDescriptor(); - ois.close(); - assertEquals(desc.getClass(), obj.getClass()); + ByteArrayInputStream bais = new ByteArrayInputStream(bytes); + ObjectInputStreamWithReadDesc1 ois = new ObjectInputStreamWithReadDesc1( + bais); + Object obj = ois.readClassDescriptor(); + ois.close(); + assertEquals(desc.getClass(), obj.getClass()); //eof bais = new ByteArrayInputStream(bytes); ExceptionalBufferedInputStream bis = new ExceptionalBufferedInputStream( bais); - ois = new ObjectIutputStreamWithReadDesc1(bis); + ois = new ObjectInputStreamWithReadDesc1(bis); bis.setEOF(true); @@ -838,7 +1175,7 @@ public class ObjectInputStreamTest extends TestCase implements //throw exception bais = new ByteArrayInputStream(bytes); bis = new ExceptionalBufferedInputStream(bais); - ois = new ObjectIutputStreamWithReadDesc1(bis); + ois = new ObjectInputStreamWithReadDesc1(bis); bis.setException(new IOException()); @@ -853,7 +1190,7 @@ public class ObjectInputStreamTest extends TestCase implements //corrupt bais = new ByteArrayInputStream(bytes); bis = new ExceptionalBufferedInputStream(bais); - ois = new ObjectIutputStreamWithReadDesc1(bis); + ois = new ObjectInputStreamWithReadDesc1(bis); bis.setCorrupt(true); @@ -864,7 +1201,7 @@ public class ObjectInputStreamTest extends TestCase implements } finally { ois.close(); } - } + } static class ExceptionalBufferedInputStream extends BufferedInputStream { private boolean eof = false; @@ -1000,26 +1337,15 @@ public class ObjectInputStreamTest extends TestCase implements //Regression Test for HARMONY-3726 public void test_readObject_array() throws Exception { - - final String resourcePrefix = ObjectInputStreamTest.class.getPackage().getName().replace('.', '/'); - -// ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/temp/test_array_strings.ser")); -// TestArray ta = new TestArray(new String[] { "AAA", "BBB" }); -// oos.writeObject(ta); -// oos.close(); -// oos = new ObjectOutputStream(new FileOutputStream("/temp/test_array_integers.ser")); -// ta = new TestArray(new Integer[] { 10, 20 }); -// oos.writeObject(ta); -// oos.close(); - + final String resourcePrefix = "serialization/org/apache/harmony/luni/tests/java/io"; ObjectInputStream oin = new ObjectInputStream(this.getClass().getClassLoader().getResourceAsStream( - "serialization/" + resourcePrefix + "/test_array_strings.ser")); - TestArray testArray = (TestArray) oin.readObject(); + resourcePrefix + "/test_array_strings.ser")); + org.apache.harmony.luni.tests.java.io.TestArray testArray = (TestArray) oin.readObject(); String[] strings = new String[] { "AAA", "BBB" }; assertTrue(java.util.Arrays.equals(strings, testArray.array)); oin = new ObjectInputStream(this.getClass().getClassLoader().getResourceAsStream( - "serialization/" + resourcePrefix + "/test_array_integers.ser")); + resourcePrefix + "/test_array_integers.ser")); testArray = (TestArray) oin.readObject(); Integer[] integers = new Integer[] { 10, 20 }; assertTrue(java.util.Arrays.equals(integers, testArray.array)); @@ -1046,7 +1372,8 @@ public class ObjectInputStreamTest extends TestCase implements @Override protected void writeClassDescriptor(ObjectStreamClass osc) throws IOException { - objs[pos++] = osc; } + objs[pos++] = osc; + } } static class TestObjectInputStream extends ObjectInputStream { @@ -1078,6 +1405,27 @@ public class ObjectInputStreamTest extends TestCase implements oin.readObject(); } + public void test_readObject_replacedClassField() throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(out); + FieldReplacementTestClass obj = new FieldReplacementTestClass(1234); + oos.writeObject(obj); + out.flush(); + out.close(); + + ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); + ObjectInputStream ois = new ObjectInputStream(in); + + try { + FieldReplacementTestClass result = + (FieldReplacementTestClass) ois.readObject(); + fail("should throw ClassCastException"); + } catch (ClassCastException e) { + // expected + } + ois.close(); + } + /** * Sets up the fixture, for example, open a network connection. This method * is called before a test is executed. @@ -1087,10 +1435,40 @@ public class ObjectInputStreamTest extends TestCase implements super.setUp(); oos = new ObjectOutputStream(bao = new ByteArrayOutputStream()); } + + public static class FieldReplacementTestClass implements Serializable { + private FieldClass c; + + public FieldReplacementTestClass(int i) { + super(); + c = new FieldClass(i); + } + } + + public static class FieldClass implements Serializable { + private int i; + + public FieldClass(int i) { + super(); + this.i = i; + } + + protected Object writeReplace() throws ObjectStreamException { + return new ReplacementFieldClass(i); + } + } + + public static class ReplacementFieldClass implements Serializable { + private int i; + + public ReplacementFieldClass(int i) { + super(); + this.i = i; + } + } } -class TestArray implements Serializable -{ +class TestArray implements Serializable { private static final long serialVersionUID = 1L; public Object[] array; @@ -1098,20 +1476,19 @@ class TestArray implements Serializable public TestArray(Object[] array) { this.array = array; } - } class Test implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - Class classes[] = new Class[] { byte.class, short.class, int.class, - long.class, boolean.class, char.class, float.class, double.class }; + Class<?> classes[] = new Class[] { byte.class, short.class, int.class, + long.class, boolean.class, char.class, float.class, double.class }; - @Override + @Override public boolean equals(Object o) { - if (!(o instanceof Test)) { - return false; - } - return Arrays.equals(classes, ((Test) o).classes); - } + if (!(o instanceof Test)) { + return false; + } + return Arrays.equals(classes, ((Test) o).classes); + } } diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/ContentHandlerFactoryTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/ContentHandlerFactoryTest.java deleted file mode 100644 index 74b2276..0000000 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/ContentHandlerFactoryTest.java +++ /dev/null @@ -1,147 +0,0 @@ -package org.apache.harmony.luni.tests.java.net; - -import dalvik.annotation.SideEffect; - -import junit.framework.TestCase; - -import tests.support.Support_Configuration; - -import java.io.IOException; -import java.lang.reflect.Field; -import java.net.ContentHandler; -import java.net.ContentHandlerFactory; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; - -public class ContentHandlerFactoryTest extends TestCase { - - ContentHandlerFactory oldFactory = null; - Field factoryField = null; - - boolean isTestable = false; - - boolean isGetContentCalled = false; - boolean isCreateContentHandlerCalled = false; - - @SideEffect("This test affects tests that are run after this one." + - " The reason are side effects due to caching in URLConnection." + - " Maybe this test needs to be run in isolation.") - public void test_createContentHandler() throws IOException { - - TestContentHandlerFactory factory = new TestContentHandlerFactory(); - - if(isTestable) { - - assertFalse(isCreateContentHandlerCalled); - - URL url = new URL("http://" + - Support_Configuration.SpecialInetTestAddress); - - URLConnection.setContentHandlerFactory(factory); - - URLConnection con = url.openConnection(); - - try { - con.getContent(); - assertTrue(isCreateContentHandlerCalled); - assertTrue(isGetContentCalled); - } catch (Exception e) { - throw new RuntimeException(e); - } - - isGetContentCalled = false; - - try { - con.getContent(new Class[] {}); - assertTrue(isGetContentCalled); - } catch (Exception e) { - throw new RuntimeException(e); - } - - try { - con.setContentHandlerFactory(factory); - fail("java.lang.Error was not thrown."); - } catch(java.lang.Error e) { - //expected - } - - try { - con.setContentHandlerFactory(null); - fail("java.lang.Error was not thrown."); - } catch(java.lang.Error e) { - //expected - } - - } else { - ContentHandler ch = factory.createContentHandler("text/plain"); - URL url; - try { - url = new URL("http://" + - Support_Configuration.SpecialInetTestAddress); - assertNotNull(ch.getContent(url.openConnection())); - } catch (MalformedURLException e) { - fail("MalformedURLException was thrown: " + e.getMessage()); - } catch (IOException e) { - fail("IOException was thrown."); - } - } - } - - public void setUp() { - Field [] fields = URLConnection.class.getDeclaredFields(); - int counter = 0; - for (Field field : fields) { - if (ContentHandlerFactory.class.equals(field.getType())) { - counter++; - factoryField = field; - } - } - - if(counter == 1) { - - isTestable = true; - - factoryField.setAccessible(true); - try { - oldFactory = (ContentHandlerFactory) factoryField.get(null); - } catch (IllegalArgumentException e) { - fail("IllegalArgumentException was thrown during setUp: " - + e.getMessage()); - } catch (IllegalAccessException e) { - fail("IllegalAccessException was thrown during setUp: " - + e.getMessage()); - } - } - } - - public void tearDown() { - if(isTestable) { - try { - factoryField.set(null, oldFactory); - } catch (IllegalArgumentException e) { - fail("IllegalArgumentException was thrown during tearDown: " - + e.getMessage()); - } catch (IllegalAccessException e) { - fail("IllegalAccessException was thrown during tearDown: " - + e.getMessage()); - } - } - } - - public class TestContentHandler extends ContentHandler { - - public Object getContent(URLConnection u) { - isGetContentCalled = true; - return null; - } - } - - public class TestContentHandlerFactory implements ContentHandlerFactory { - - public ContentHandler createContentHandler(String mimetype) { - isCreateContentHandlerCalled = true; - return new TestContentHandler(); - } - } -} diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLConnectionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLConnectionTest.java index d1674f3..5307cf4 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLConnectionTest.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLConnectionTest.java @@ -16,7 +16,6 @@ package org.apache.harmony.luni.tests.java.net; -import dalvik.annotation.BrokenTest; import junit.framework.TestCase; import tests.support.Support_Configuration; import tests.support.Support_TestWebData; @@ -209,10 +208,14 @@ public class URLConnectionTest extends TestCase { URL url2; + URL url3; + URLConnection uc; URLConnection uc2; + URLConnection uc3; + Support_TestWebServer server; @Override @@ -225,6 +228,8 @@ public class URLConnectionTest extends TestCase { uc = url.openConnection(); url2 = new URL("http://localhost:" + port + "/test2"); uc2 = url2.openConnection(); + url3 = new URL("http://localhost:" + port + "/test3"); + uc3 = url3.openConnection(); fileURL = createTempHelloWorldFile(); fileURLCon = fileURL.openConnection(); @@ -239,6 +244,7 @@ public class URLConnectionTest extends TestCase { server.close(); ((HttpURLConnection) uc).disconnect(); ((HttpURLConnection) uc2).disconnect(); + ((HttpURLConnection) uc3).disconnect(); } /** @@ -432,39 +438,6 @@ public class URLConnectionTest extends TestCase { } /** - * @throws IOException - * {@link java.net.URLConnection#getContentEncoding()} - */ - @BrokenTest("Fails in CTS, passes in CoreTestRunner") - public void test_getContentEncoding() throws IOException { - // faulty setup - try { - - fileURLCon.getContentEncoding(); - fail("Exception expected"); - } catch (Throwable e) { - //ok - } - - // positive case - - URL url = new URL("http://www.amazon.com/"); - - URLConnection con = url.openConnection(); - con.setRequestProperty("Accept-Encoding", "gzip"); - con.connect(); - - assertEquals(con.getContentEncoding(), "gzip"); - - - uc2.setRequestProperty("Accept-Encoding", "bla"); - uc2.connect(); - - assertNull(uc2.getContentEncoding()); - - } - - /** * {@link java.net.URLConnection#getContentLength()} */ public void test_getContentLength() throws Exception { @@ -472,8 +445,8 @@ public class URLConnectionTest extends TestCase { assertEquals(Support_TestWebData.test1.length, uc.getContentLength()); assertEquals(Support_TestWebData.test2.length, uc2.getContentLength()); - assertNotNull(jarURLCon.getContentLength()); - assertNotNull(gifURLCon.getContentLength()); + assertTrue(jarURLCon.getContentLength() > 0); + assertTrue(gifURLCon.getContentLength() > 0); fileURLCon.getInputStream().close(); } @@ -719,17 +692,17 @@ public class URLConnectionTest extends TestCase { } /** - * @throws IOException * {@link java.net.URLConnection#getHeaderFieldInt(String, int)} */ public void test_getHeaderFieldInt() throws IOException, ParseException { - Support_TestWebData params = Support_TestWebData.testParams[1]; + // Test getHeaderFieldInt() can read an int value. + Support_TestWebData params1 = Support_TestWebData.testParams[1]; + int hf = uc2.getHeaderFieldInt("Content-Length", Integer.MIN_VALUE); + assertEquals(params1.testLength, hf); - int hf = 0; + // The remaining fields should be invalid or missing. Confirm the default is returned. hf = uc2.getHeaderFieldInt("Content-Encoding", Integer.MIN_VALUE); assertEquals(Integer.MIN_VALUE, hf); - hf = uc2.getHeaderFieldInt("Content-Length", Integer.MIN_VALUE); - assertEquals(params.testLength, hf); hf = uc2.getHeaderFieldInt("Content-Type", Integer.MIN_VALUE); assertEquals(Integer.MIN_VALUE, hf); hf = uc2.getHeaderFieldInt("Date", Integer.MIN_VALUE); @@ -745,6 +718,10 @@ public class URLConnectionTest extends TestCase { hf = uc2.getHeaderFieldInt("DoesNotExist", Integer.MIN_VALUE); assertEquals(Integer.MIN_VALUE, hf); + // Test getHeaderFieldInt() for a value outside of the range of int. + Support_TestWebData params2 = Support_TestWebData.testParams[2]; + hf = uc3.getHeaderFieldInt("Content-Length", Integer.MIN_VALUE); + assertEquals(Integer.MIN_VALUE, hf); } /** @@ -823,34 +800,6 @@ public class URLConnectionTest extends TestCase { } } - /** - * @throws IOException - * {@link java.net.URLConnection#getLastModified()} - */ - public void test_getLastModified() throws IOException { - - URL url4 = new URL(Support_Configuration.hTTPURLwLastModified); - URLConnection uc4 = url4.openConnection(); - - uc4.connect(); - - if (uc4.getLastModified() == 0) { - System.out - .println("WARNING: Server does not support 'Last-Modified', test_getLastModified() not run"); - return; - } - - long millis = uc4.getHeaderFieldDate("Last-Modified", 0); - - assertEquals( - "Returned wrong getLastModified value. Wanted: " - + " got: " + uc4.getLastModified(), - millis, uc4.getLastModified()); - - - ((HttpURLConnection) uc).disconnect(); - } - public void test_getOutputStream_failAfterDisconnect() throws IOException { ((HttpURLConnection) uc2).disconnect(); @@ -1253,7 +1202,7 @@ public class URLConnectionTest extends TestCase { String cts = System.getProperty("java.io.tmpdir"); File tmpDir = new File(cts); Support_Resources.copyFile(tmpDir, null, "Harmony.GIF"); - URL fUrl1 = new URL("file:/" + tmpDir.getPath() + URL fUrl1 = new URL("file://" + tmpDir.getPath() + "/Harmony.GIF"); URLConnection con1 = fUrl1.openConnection(); return con1; diff --git a/luni/src/test/java/org/apache/harmony/security/tests/java/security/KeyStoreTest.java b/luni/src/test/java/org/apache/harmony/security/tests/java/security/KeyStoreTest.java index a158c83..6b93abe 100644 --- a/luni/src/test/java/org/apache/harmony/security/tests/java/security/KeyStoreTest.java +++ b/luni/src/test/java/org/apache/harmony/security/tests/java/security/KeyStoreTest.java @@ -228,9 +228,6 @@ public class KeyStoreTest extends TestCase { } } - /** - * @test java.security.KeyStore.PasswordProtection.getPassword() - */ public void testKeyStorePPGetPassword() { // Regression for HARMONY-1539 // no exception expected diff --git a/luni/src/test/java/org/apache/harmony/security/tests/java/security/ProviderServiceTest.java b/luni/src/test/java/org/apache/harmony/security/tests/java/security/ProviderServiceTest.java index bef27ba..f939730 100644 --- a/luni/src/test/java/org/apache/harmony/security/tests/java/security/ProviderServiceTest.java +++ b/luni/src/test/java/org/apache/harmony/security/tests/java/security/ProviderServiceTest.java @@ -124,13 +124,6 @@ public class ProviderServiceTest extends TestCase { Object o = s.newInstance(null); assertTrue("incorrect instance", o instanceof RandomImpl); - - try { - o = s.newInstance(new Object()); - fail("No expected NoSuchAlgorithmException"); - } catch (NoSuchAlgorithmException e) { - } - } public void testGetAlgorithm() { diff --git a/luni/src/test/java/org/apache/harmony/security/tests/java/security/Signature2Test.java b/luni/src/test/java/org/apache/harmony/security/tests/java/security/Signature2Test.java index 7886e3e..ad084e1 100644 --- a/luni/src/test/java/org/apache/harmony/security/tests/java/security/Signature2Test.java +++ b/luni/src/test/java/org/apache/harmony/security/tests/java/security/Signature2Test.java @@ -68,7 +68,17 @@ public class Signature2Test extends junit.framework.TestCase { * java.security.Signature#clone() */ public void test_clone() throws Exception { + // A Signature may be cloneable according to the API, in practice the implementation isn't + // once it has been initialized. Checking for runtime exceptions rather than useful + // behavior. Signature s = Signature.getInstance("DSA"); + Signature clone = (Signature) s.clone(); + assertNotNull(clone); + assertEquals(s.getAlgorithm(), clone.getAlgorithm()); + assertEquals(s.getProvider(), clone.getProvider()); + + KeyPair keyPair = getDsaKeys(); + s.initSign(keyPair.getPrivate()); try { s.clone(); fail(); diff --git a/luni/src/test/java/tests/api/java/io/ComputeSerialVersionUIDTest.java b/luni/src/test/java/tests/api/java/io/ComputeSerialVersionUIDTest.java deleted file mode 100644 index 458c27f..0000000 --- a/luni/src/test/java/tests/api/java/io/ComputeSerialVersionUIDTest.java +++ /dev/null @@ -1,145 +0,0 @@ -package tests.api.java.io; - -import java.io.ObjectInputStream; - -public class ComputeSerialVersionUIDTest extends junit.framework.TestCase { - - - private String path = "/serialization/tests/api/java/io/"; - - public void testComputeSUIDClass() throws Exception { - ObjectInputStream ois = new ObjectInputStream(getClass() - .getResourceAsStream(path + "testComputeSUIDClass.ser")); - SerializationTestClass.TestClassName1 o1 = (SerializationTestClass.TestClassName1) ois - .readObject(); - SerializationTestClass.TestClassName2T_T$T o2 = (SerializationTestClass.TestClassName2T_T$T) ois - .readObject(); - SerializationTestClass.TestClassModifierPublic o6 = (SerializationTestClass.TestClassModifierPublic) ois - .readObject(); - SerializationTestClass.TestClassModifierAbstract o3 = (SerializationTestClass.TestClassModifierAbstract) ois - .readObject(); - SerializationTestClass.TestClassModifierFinal o4 = (SerializationTestClass.TestClassModifierFinal) ois - .readObject(); - SerializationTestClass.TestClassModifierInterface o5 = (SerializationTestClass.TestClassModifierInterface) ois - .readObject(); - ois.close(); - } - - public void testComputeSUIDInterfaces() throws Exception { - ObjectInputStream ois = new ObjectInputStream(getClass() - .getResourceAsStream(path + "testComputeSUIDInterfaces.ser")); - SerializationTestClass.TestIntefaces o1 = (SerializationTestClass.TestIntefaces) ois - .readObject(); - SerializationTestClass.TestIntefacesA o2 = (SerializationTestClass.TestIntefacesA) ois - .readObject(); - SerializationTestClass.TestIntefacesAB o3 = (SerializationTestClass.TestIntefacesAB) ois - .readObject(); - SerializationTestClass.TestIntefacesBA o4 = (SerializationTestClass.TestIntefacesBA) ois - .readObject(); - SerializationTestClass.TestIntefacesC o5 = (SerializationTestClass.TestIntefacesC) ois - .readObject(); - SerializationTestClass.TestIntefacesAC o6 = (SerializationTestClass.TestIntefacesAC) ois - .readObject(); - SerializationTestClass.TestIntefacesCA o7 = (SerializationTestClass.TestIntefacesCA) ois - .readObject(); - SerializationTestClass.TestIntefacesABC o8 = (SerializationTestClass.TestIntefacesABC) ois - .readObject(); - SerializationTestClass.TestIntefacesACB o9 = (SerializationTestClass.TestIntefacesACB) ois - .readObject(); - SerializationTestClass.TestIntefacesBAC o10 = (SerializationTestClass.TestIntefacesBAC) ois - .readObject(); - SerializationTestClass.TestIntefacesBCA o11 = (SerializationTestClass.TestIntefacesBCA) ois - .readObject(); - SerializationTestClass.TestIntefacesCAB o12 = (SerializationTestClass.TestIntefacesCAB) ois - .readObject(); - SerializationTestClass.TestIntefacesCBA o13 = (SerializationTestClass.TestIntefacesCBA) ois - .readObject(); - ois.close(); - } - - public void testComputeSUIDFields() throws Exception { - ObjectInputStream ois = new ObjectInputStream(getClass() - .getResourceAsStream(path + "testComputeSUIDFields.ser")); - SerializationTestClass.TestFieldsNone o1 = (SerializationTestClass.TestFieldsNone) ois - .readObject(); - SerializationTestClass.TestFieldsOneFinal o2 = (SerializationTestClass.TestFieldsOneFinal) ois - .readObject(); - SerializationTestClass.TestFieldsTwoFinal o3 = (SerializationTestClass.TestFieldsTwoFinal) ois - .readObject(); - SerializationTestClass.TestFieldsOnePrivate o4 = (SerializationTestClass.TestFieldsOnePrivate) ois - .readObject(); - SerializationTestClass.TestFieldsTwoPrivate o5 = (SerializationTestClass.TestFieldsTwoPrivate) ois - .readObject(); - SerializationTestClass.TestFieldsOneProtected o6 = (SerializationTestClass.TestFieldsOneProtected) ois - .readObject(); - SerializationTestClass.TestFieldsTwoProtected o7 = (SerializationTestClass.TestFieldsTwoProtected) ois - .readObject(); - SerializationTestClass.TestFieldsOnePublic o8 = (SerializationTestClass.TestFieldsOnePublic) ois - .readObject(); - SerializationTestClass.TestFieldsTwoPublic o9 = (SerializationTestClass.TestFieldsTwoPublic) ois - .readObject(); - SerializationTestClass.TestFieldsOneStatic o10 = (SerializationTestClass.TestFieldsOneStatic) ois - .readObject(); - SerializationTestClass.TestFieldsTwoStatic o11 = (SerializationTestClass.TestFieldsTwoStatic) ois - .readObject(); - SerializationTestClass.TestFieldsOneTransient o12 = (SerializationTestClass.TestFieldsOneTransient) ois - .readObject(); - SerializationTestClass.TestFieldsTwoTransient o13 = (SerializationTestClass.TestFieldsTwoTransient) ois - .readObject(); - SerializationTestClass.TestFieldsOneVolatile o14 = (SerializationTestClass.TestFieldsOneVolatile) ois - .readObject(); - SerializationTestClass.TestFieldsTwoVolatile o15 = (SerializationTestClass.TestFieldsTwoVolatile) ois - .readObject(); - SerializationTestClass.TestFieldSignatures o16 = (SerializationTestClass.TestFieldSignatures) ois - .readObject(); - ois.close(); - } - - public void testComputeSUIDConstructors() throws Exception { - ObjectInputStream ois = new ObjectInputStream(getClass() - .getResourceAsStream(path + "testComputeSUIDConstructors.ser")); - SerializationTestClass.TestConstructorNone o1 = (SerializationTestClass.TestConstructorNone) ois - .readObject(); - SerializationTestClass.TestConstructorOne o2 = (SerializationTestClass.TestConstructorOne) ois - .readObject(); - SerializationTestClass.TestConstructorPrivate o3 = (SerializationTestClass.TestConstructorPrivate) ois - .readObject(); - SerializationTestClass.TestConstructorProtected o4 = (SerializationTestClass.TestConstructorProtected) ois - .readObject(); - SerializationTestClass.TestConstructorPublic o5 = (SerializationTestClass.TestConstructorPublic) ois - .readObject(); - SerializationTestClass.TestConstructorSignature o6 = (SerializationTestClass.TestConstructorSignature) ois - .readObject(); - SerializationTestClass.TestConstructorTwo o7 = (SerializationTestClass.TestConstructorTwo) ois - .readObject(); - SerializationTestClass.TestConstructorTwoReverse o8 = (SerializationTestClass.TestConstructorTwoReverse) ois - .readObject(); - ois.close(); - } - - public void testComputeSUIDMethods() throws Exception { - ObjectInputStream ois = new ObjectInputStream(getClass() - .getResourceAsStream(path + "testComputeSUIDMethods.ser")); - SerializationTestClass.TestMehodPrivate o1 = (SerializationTestClass.TestMehodPrivate) ois - .readObject(); - SerializationTestClass.TestMethodAbstract o2 = (SerializationTestClass.TestMethodAbstract) ois - .readObject(); - SerializationTestClass.TestMethodFinal o3 = (SerializationTestClass.TestMethodFinal) ois - .readObject(); - SerializationTestClass.TestMethodNative o4 = (SerializationTestClass.TestMethodNative) ois - .readObject(); - SerializationTestClass.TestMethodProtected o5 = (SerializationTestClass.TestMethodProtected) ois - .readObject(); - SerializationTestClass.TestMethodPublic o6 = (SerializationTestClass.TestMethodPublic) ois - .readObject(); - SerializationTestClass.TestMethodStatic o7 = (SerializationTestClass.TestMethodStatic) ois - .readObject(); - SerializationTestClass.TestMethodSignature o9 = (SerializationTestClass.TestMethodSignature) ois - .readObject(); - SerializationTestClass.TestMethodReturnSignature o10 = (SerializationTestClass.TestMethodReturnSignature) ois - .readObject(); - SerializationTestClass.TestMethodSynchronized o8 = (SerializationTestClass.TestMethodSynchronized) ois - .readObject(); - ois.close(); - } -} diff --git a/luni/src/test/java/tests/api/java/io/ObjectInputStreamTest.java b/luni/src/test/java/tests/api/java/io/ObjectInputStreamTest.java deleted file mode 100644 index 434d31c..0000000 --- a/luni/src/test/java/tests/api/java/io/ObjectInputStreamTest.java +++ /dev/null @@ -1,687 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.io; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.ObjectStreamClass; -import java.io.OutputStream; -import java.io.Serializable; -import java.io.StreamCorruptedException; -import java.util.Arrays; -import java.util.Hashtable; -import java.util.Vector; -import org.apache.harmony.testframework.serialization.SerializationTest; -import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; -import tests.support.Support_ASimpleInputStream; - -public class ObjectInputStreamTest extends junit.framework.TestCase implements - Serializable { - - static final long serialVersionUID = 1L; - - ObjectInputStream ois; - - ObjectOutputStream oos; - - ByteArrayOutputStream bao; - - boolean readStreamHeaderCalled; - - private final String testString = "Lorem ipsum..."; - - private final int testLength = testString.length(); - - public void test_ConstructorLjava_io_InputStream_IOException() throws IOException { - oos.writeObject(testString); - oos.close(); - - Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray()); - sis.throwExceptionOnNextUse = true; - try { - ois = new ObjectInputStream(sis); - fail("Test 1: IOException expected."); - } catch (IOException e) { - // Expected. - } - sis.throwExceptionOnNextUse = false; - } - - public void test_ClassDescriptor() throws IOException, - ClassNotFoundException { - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStreamWithWriteDesc oos = new ObjectOutputStreamWithWriteDesc( - baos); - oos.writeObject(String.class); - oos.close(); - Class<?> cls = TestClassForSerialization.class; - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - ObjectInputStreamWithReadDesc ois = new ObjectInputStreamWithReadDesc( - bais, cls); - Object obj = ois.readObject(); - ois.close(); - assertEquals(cls, obj); - } - - public void test_available() throws IOException { - // Test for method int java.io.ObjectInputStream.available() - oos.writeBytes(testString); - oos.close(); - - Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray()); - ois = new ObjectInputStream(sis); - assertEquals("Test 1: Incorrect number of bytes;", testLength, ois.available()); - ois.close(); - } - - public void test_available_IOException() throws IOException { - oos.writeObject(testString); - oos.close(); - - Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray()); - ois = new ObjectInputStream(sis); - sis.throwExceptionOnNextUse = true; - try { - ois.available(); - fail("Test 1: IOException expected."); - } catch (IOException e) { - // Expected. - } - sis.throwExceptionOnNextUse = false; - ois.close(); - } - - public void test_close() throws Exception { - // Test for method void java.io.ObjectInputStream.close() - oos.writeObject(testString); - oos.close(); - - Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray()); - ois = new ObjectInputStream(sis); - sis.throwExceptionOnNextUse = true; - try { - ois.close(); - fail("Test 1: IOException expected."); - } catch (IOException e) { - // Expected. - } - sis.throwExceptionOnNextUse = false; - ois.close(); - } - - public void test_enableResolveObjectB() throws IOException { - // Start testing without a SecurityManager. - BasicObjectInputStream bois = new BasicObjectInputStream(); - assertFalse("Test 1: Object resolving must be disabled by default.", - bois.enableResolveObject(true)); - - assertTrue("Test 2: enableResolveObject did not return the previous value.", - bois.enableResolveObject(false)); - } - - public void test_read_IOException() throws IOException { - oos.writeObject(testString); - oos.close(); - - Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray()); - ois = new ObjectInputStream(sis); - sis.throwExceptionOnNextUse = true; - try { - ois.read(); - fail("Test 1: IOException expected."); - } catch (IOException e) { - // Expected. - } - sis.throwExceptionOnNextUse = false; - ois.close(); - } - - public void test_read$BII() throws IOException { - // Test for method int java.io.ObjectInputStream.read(byte [], int, int) - byte[] buf = new byte[testLength]; - oos.writeBytes(testString); - oos.close(); - ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); - ois.read(buf, 0, testLength); - ois.close(); - assertEquals("Read incorrect bytes", testString, new String(buf)); - } - - public void test_read$BII_Exception() throws IOException { - byte[] buf = new byte[testLength]; - oos.writeObject(testString); - oos.close(); - - ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); - try { - ois.read(buf, 0, -1); - fail("IndexOutOfBoundsException was not thrown."); - } catch (IndexOutOfBoundsException e) { - // Expected - } - try { - ois.read(buf, -1,1); - fail("IndexOutOfBoundsException was not thrown."); - } catch (IndexOutOfBoundsException e) { - // Expected - } - try { - ois.read(buf, testLength, 1); - fail("IndexOutOfBoundsException was not thrown."); - } catch (IndexOutOfBoundsException e) { - // Expected - } - ois.close(); - - - Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray()); - ois = new ObjectInputStream(sis); - sis.throwExceptionOnNextUse = true; - try { - ois.read(buf, 0, testLength); - fail("Test 1: IOException expected."); - } catch (IOException e) { - // Expected. - } - sis.throwExceptionOnNextUse = false; - ois.close(); - } - - public void test_readFully$B() throws IOException { - byte[] buf = new byte[testLength]; - oos.writeBytes(testString); - oos.close(); - ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); - ois.readFully(buf); - assertEquals("Test 1: Incorrect bytes read;", - testString, new String(buf)); - ois.close(); - - ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); - ois.read(); - try { - ois.readFully(buf); - fail("Test 2: EOFException expected."); - } catch (EOFException e) { - // Expected. - } - } - - public void test_readFully$B_Exception() throws IOException { - byte[] buf = new byte[testLength]; - oos.writeObject(testString); - oos.close(); - - Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray()); - ois = new ObjectInputStream(sis); - sis.throwExceptionOnNextUse = true; - try { - ois.readFully(buf); - fail("Test 1: IOException expected."); - } catch (IOException e) { - // Expected. - } - sis.throwExceptionOnNextUse = false; - ois.close(); - } - - public void test_readFully$BII() throws IOException { - // Test for method void java.io.ObjectInputStream.readFully(byte [], - // int, int) - byte[] buf = new byte[testLength]; - oos.writeBytes(testString); - oos.close(); - ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); - ois.readFully(buf, 0, testLength); - assertEquals("Read incorrect bytes", testString, new String(buf)); - ois.close(); - - ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); - ois.read(); - try { - ois.readFully(buf); - fail("Test 2: EOFException expected."); - } catch (EOFException e) { - // Expected. - } - } - - public void test_readFully$BII_Exception() throws IOException { - byte[] buf = new byte[testLength]; - oos.writeObject(testString); - oos.close(); - - ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); - try { - ois.readFully(buf, 0, -1); - fail("IndexOutOfBoundsException was not thrown."); - } catch (IndexOutOfBoundsException e) { - // Expected - } - try { - ois.readFully(buf, -1,1); - fail("IndexOutOfBoundsException was not thrown."); - } catch (IndexOutOfBoundsException e) { - // Expected - } - try { - ois.readFully(buf, testLength, 1); - fail("IndexOutOfBoundsException was not thrown."); - } catch (IndexOutOfBoundsException e) { - // Expected - } - ois.close(); - - Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray()); - ois = new ObjectInputStream(sis); - sis.throwExceptionOnNextUse = true; - try { - ois.readFully(buf, 0, 1); - fail("Test 1: IOException expected."); - } catch (IOException e) { - // Expected. - } - sis.throwExceptionOnNextUse = false; - ois.close(); - } - - @SuppressWarnings("deprecation") - public void test_readLine() throws IOException { - String line; - oos.writeBytes("Lorem\nipsum\rdolor sit amet..."); - oos.close(); - - ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); - line = ois.readLine(); - assertTrue("Test 1: Incorrect line written or read: " + line, - line.equals("Lorem")); - line = ois.readLine(); - assertTrue("Test 2: Incorrect line written or read: " + line, - line.equals("ipsum")); - line = ois.readLine(); - assertTrue("Test 3: Incorrect line written or read: " + line, - line.equals("dolor sit amet...")); - ois.close(); - } - - public void test_readLine_IOException() throws IOException { - oos.writeObject(testString); - oos.close(); - - Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray()); - ois = new ObjectInputStream(sis); - sis.throwExceptionOnNextUse = true; - try { - ois.readLine(); - fail("Test 1: IOException expected."); - } catch (IOException e) { - // Expected. - } - sis.throwExceptionOnNextUse = false; - ois.close(); - } - - private void fillStreamHeader(byte[] buffer) { - short magic = java.io.ObjectStreamConstants.STREAM_MAGIC; - short version = java.io.ObjectStreamConstants.STREAM_VERSION; - - if (buffer.length < 4) { - throw new IllegalArgumentException("The buffer's minimal length must be 4."); - } - - // Initialize the buffer with the correct header for object streams - buffer[0] = (byte) (magic >> 8); - buffer[1] = (byte) magic; - buffer[2] = (byte) (version >> 8); - buffer[3] = (byte) (version); - } - - public void test_readObjectOverride() throws Exception { - byte[] buffer = new byte[4]; - - // Initialize the buffer with the correct header for object streams - fillStreamHeader(buffer); - - // Test 1: Check that readObjectOverride() returns null if there - // is no input stream. - BasicObjectInputStream bois = new BasicObjectInputStream(); - assertNull("Test 1:", bois.readObjectOverride()); - - // Test 2: Check that readObjectOverride() throws an IOException - // if there is an input stream. - bois = new BasicObjectInputStream(new ByteArrayInputStream(buffer)); - try { - bois.readObjectOverride(); - fail("Test 2: IOException expected."); - } catch (IOException e) {} - - bois.close(); - } - - public void test_readObjectMissingClasses() throws Exception { - SerializationTest.verifySelf(new A1(), new SerializableAssert() { - public void assertDeserialized(Serializable initial, - Serializable deserialized) { - assertEquals(5, ((A1) deserialized).b1.i); - } - }); - } - - public void test_readObjectCorrupt() { - byte[] bytes = { 00, 00, 00, 0x64, 0x43, 0x48, (byte) 0xFD, 0x71, 00, - 00, 0x0B, (byte) 0xB8, 0x4D, 0x65 }; - ByteArrayInputStream bin = new ByteArrayInputStream(bytes); - boolean exception = false; - try { - ObjectInputStream in = new ObjectInputStream(bin); - in.readObject(); - fail("Unexpected read of corrupted stream"); - } catch (StreamCorruptedException e) { - exception = true; - } catch (IOException e) { - fail("Unexpected: " + e); - } catch (ClassNotFoundException e) { - fail("Unexpected: " + e); - } - assertTrue("Expected StreamCorruptedException", exception); - } - - public void test_readStreamHeader() throws IOException { - String testString = "Lorem ipsum"; - BasicObjectInputStream bois; - short magic = java.io.ObjectStreamConstants.STREAM_MAGIC; - short version = java.io.ObjectStreamConstants.STREAM_VERSION; - byte[] buffer = new byte[20]; - - // Initialize the buffer with the correct header for object streams - fillStreamHeader(buffer); - System.arraycopy(testString.getBytes(), 0, buffer, 4, testString.length()); - - // Test 1: readStreamHeader should not throw a StreamCorruptedException. - // It should get called by the ObjectInputStream constructor. - try { - readStreamHeaderCalled = false; - bois = new BasicObjectInputStream(new ByteArrayInputStream(buffer)); - bois.close(); - } catch (StreamCorruptedException e) { - fail("Test 1: Unexpected StreamCorruptedException."); - } - assertTrue("Test 1: readStreamHeader() has not been called.", - readStreamHeaderCalled); - - // Test 2: Make the stream magic number invalid and check that - // readStreamHeader() throws an exception. - buffer[0] = (byte)magic; - buffer[1] = (byte)(magic >> 8); - try { - readStreamHeaderCalled = false; - bois = new BasicObjectInputStream(new ByteArrayInputStream(buffer)); - fail("Test 2: StreamCorruptedException expected."); - bois.close(); - } catch (StreamCorruptedException e) { - } - assertTrue("Test 2: readStreamHeader() has not been called.", - readStreamHeaderCalled); - - // Test 3: Make the stream version invalid and check that - // readStreamHeader() throws an exception. - buffer[0] = (byte)(magic >> 8); - buffer[1] = (byte)magic; - buffer[2] = (byte)(version); - buffer[3] = (byte)(version >> 8); - try { - readStreamHeaderCalled = false; - bois = new BasicObjectInputStream(new ByteArrayInputStream(buffer)); - fail("Test 3: StreamCorruptedException expected."); - bois.close(); - } catch (StreamCorruptedException e) { - } - assertTrue("Test 3: readStreamHeader() has not been called.", - readStreamHeaderCalled); - } - - public void test_readUnsignedByte() throws IOException { - oos.writeByte(-1); - oos.close(); - - ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); - assertEquals("Test 1: Incorrect unsigned byte written or read.", - 255, ois.readUnsignedByte()); - - try { - ois.readUnsignedByte(); - fail("Test 2: EOFException expected."); - } catch (EOFException e) { - // Expected. - } - - ois.close(); - try { - ois.readUnsignedByte(); - fail("Test 3: IOException expected."); - } catch (IOException e) { - // Expected. - } - } - - public void test_readUnsignedShort() throws IOException { - // Test for method int java.io.ObjectInputStream.readUnsignedShort() - oos.writeShort(-1); - oos.close(); - - ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray())); - assertEquals("Test 1: Incorrect unsigned short written or read.", - 65535, ois.readUnsignedShort()); - - try { - ois.readUnsignedShort(); - fail("Test 2: EOFException expected."); - } catch (EOFException e) { - // Expected. - } - - ois.close(); - try { - ois.readUnsignedShort(); - fail("Test 3: IOException expected."); - } catch (IOException e) { - // Expected. - } - } - - public void test_resolveProxyClass() throws IOException { - BasicObjectInputStream bois; - byte[] buffer = new byte[10]; - - // Initialize the buffer with the header for object streams - fillStreamHeader(buffer); - bois = new BasicObjectInputStream(new ByteArrayInputStream(buffer)); - - // Test 1: Check that a NullPointerException is thrown - // if null is passed to the method. - try { - bois.resolveProxyClass(null); - fail("Test 1: NullPointerException expected."); - } - catch (NullPointerException npe) { - } - catch (ClassNotFoundException cnfe) { - fail("Test 1: Unexpected ClassNotFoundException."); - } - - // Test 2: Check that visible interfaces are found. - try { - String[] interfaces = { "java.io.Closeable", - "java.lang.Cloneable" }; - bois.resolveProxyClass(interfaces); - } - catch (ClassNotFoundException cnfe) { - fail("Test 2: Unexpected ClassNotFoundException."); - } - - // Test 3: Check that a ClassNotFoundException is thrown if the - // array of interfaces is not valid. - try { - String[] interfaces = { "java.io.Closeable", - "java.io.Closeable" }; - bois.resolveProxyClass(interfaces); - fail ("Test 3: ClassNotFoundException expected."); - } - catch (ClassNotFoundException cnfe) { - } - - bois.close(); - } - - public void test_skipBytesI_IOException() throws IOException { - oos.writeObject(testString); - oos.close(); - - Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray()); - ois = new ObjectInputStream(sis); - sis.throwExceptionOnNextUse = true; - try { - ois.skipBytes(5); - fail("Test 1: IOException expected."); - } catch (IOException e) { - // Expected. - } - sis.throwExceptionOnNextUse = false; - ois.close(); - } - - public static class A implements Serializable { - - private static final long serialVersionUID = 11L; - - public String name = "name"; - } - - public static class B extends A {} - - public static class C extends B { - - private static final long serialVersionUID = 33L; - } - - public static class A1 implements Serializable { - - static final long serialVersionUID = 5942584913446079661L; - - B1 b1 = new B1(); - - B1 b2 = b1; - - Vector v = new Vector(); - } - - public static class B1 implements Serializable { - - int i = 5; - - Hashtable h = new Hashtable(); - } - - class BasicObjectInputStream extends ObjectInputStream { - public BasicObjectInputStream() throws IOException, SecurityException { - super(); - } - - public BasicObjectInputStream(InputStream input) throws IOException { - super(input); - } - - public boolean enableResolveObject(boolean enable) - throws SecurityException { - return super.enableResolveObject(enable); - } - - public Object readObjectOverride() throws ClassNotFoundException, IOException { - return super.readObjectOverride(); - } - - public void readStreamHeader() throws IOException { - readStreamHeaderCalled = true; - super.readStreamHeader(); - } - - public Class<?> resolveProxyClass(String[] interfaceNames) - throws IOException, ClassNotFoundException { - return super.resolveProxyClass(interfaceNames); - } - } - - //Regression Test for JIRA-2249 - public static class ObjectOutputStreamWithWriteDesc extends - ObjectOutputStream { - public ObjectOutputStreamWithWriteDesc(OutputStream os) - throws IOException { - super(os); - } - - public void writeClassDescriptor(ObjectStreamClass desc) - throws IOException { - } - } - - public static class ObjectInputStreamWithReadDesc extends - ObjectInputStream { - private Class returnClass; - - public ObjectInputStreamWithReadDesc(InputStream is, Class returnClass) - throws IOException { - super(is); - this.returnClass = returnClass; - } - - public ObjectStreamClass readClassDescriptor() throws IOException, - ClassNotFoundException { - return ObjectStreamClass.lookup(returnClass); - - } - } - - static class TestClassForSerialization implements Serializable { - private static final long serialVersionUID = 1L; - } - - protected void setUp() throws Exception { - super.setUp(); - oos = new ObjectOutputStream(bao = new ByteArrayOutputStream()); - } -} - -class Test implements Serializable { - private static final long serialVersionUID = 1L; - - Class<?> classes[] = new Class[] { byte.class, short.class, int.class, - long.class, boolean.class, char.class, float.class, double.class }; - - public boolean equals(Object o) { - if (!(o instanceof Test)) { - return false; - } - return Arrays.equals(classes, ((Test) o).classes); - } -} diff --git a/luni/src/test/java/tests/api/java/io/SerializationTestClass.java b/luni/src/test/java/tests/api/java/io/SerializationTestClass.java deleted file mode 100644 index 32c4d0b..0000000 --- a/luni/src/test/java/tests/api/java/io/SerializationTestClass.java +++ /dev/null @@ -1,335 +0,0 @@ -package tests.api.java.io; - -public class SerializationTestClass implements java.io.Serializable { - - // Test class names - public class TestClassName1 implements java.io.Serializable { - } - - public class TestClassName2T_T$T implements java.io.Serializable { - } - - // Test Modifiers - public class TestClassModifierPublic implements java.io.Serializable { - } - - interface TestClassModifierInterfaceHelper extends java.io.Serializable { - } - - public class TestClassModifierInterface implements - TestClassModifierInterfaceHelper { - } - - final class TestClassModifierFinal implements java.io.Serializable { - } - - abstract class TestClassModifierAbstractHelper implements - java.io.Serializable { - } - - public class TestClassModifierAbstract extends - TestClassModifierAbstractHelper { - } - - - // TODO Arrays always are abstract - - // TODO Non public interface has no abstract modifier - - - // Test interfaces - interface A extends java.io.Serializable { - } - - interface B extends java.io.Serializable { - } - - interface C extends A { - } - - public class TestIntefaces implements java.io.Serializable { - } - - public class TestIntefacesA implements A { - } - - public class TestIntefacesAB implements A, B { - } - - public class TestIntefacesBA implements B, A { - } - - public class TestIntefacesC implements C { - } - - public class TestIntefacesAC implements A, C { - } - - public class TestIntefacesCA implements C, A { - } - - public class TestIntefacesABC implements A, B, C { - } - - public class TestIntefacesACB implements A, C, B { - } - - public class TestIntefacesBAC implements B, A, C { - } - - public class TestIntefacesBCA implements B, C, A { - } - - public class TestIntefacesCAB implements C, A, B { - } - - public class TestIntefacesCBA implements C, B, A { - } - - /** - * Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED | Modifier.STATIC | - * Modifier.FINAL | Modifier.VOLATILE | Modifier.TRANSIENT - */ - // Test Fields - public class TestFieldsNone implements java.io.Serializable { - } - - public class TestFieldsOnePublic implements java.io.Serializable { - public int one; - } - - public class TestFieldsTwoPublic implements java.io.Serializable { - public int one; - public int two; - } - - @SuppressWarnings("unused") - public class TestFieldsOnePrivate implements java.io.Serializable { - private int one; - } - - @SuppressWarnings("unused") - public class TestFieldsTwoPrivate implements java.io.Serializable { - private int one; - private int two; - } - - public class TestFieldsOneProtected implements java.io.Serializable { - protected int one; - } - - public class TestFieldsTwoProtected implements java.io.Serializable { - protected int one; - protected int two; - } - - public static class TestFieldsOneStatic implements java.io.Serializable { - static int one; - } - - public static class TestFieldsTwoStatic implements java.io.Serializable { - static int one; - static int two; - } - - public class TestFieldsOneFinal implements java.io.Serializable { - final int one = 0; - } - - public class TestFieldsTwoFinal implements java.io.Serializable { - final int one = 0; - final int two = 0; - } - - public class TestFieldsOneVolatile implements java.io.Serializable { - volatile int one; - } - - public class TestFieldsTwoVolatile implements java.io.Serializable { - volatile int one; - volatile int two; - } - - public class TestFieldsOneTransient implements java.io.Serializable { - transient int one; - } - - public class TestFieldsTwoTransient implements java.io.Serializable { - transient int one; - transient int two; - } - - public class TestFieldSignatures implements java.io.Serializable { - Object l; - int i; - short s; - long j; - boolean z; - char c; - double d; - float f; - byte b; - } - - - // Test Constructors - public class TestConstructorNone implements java.io.Serializable { - } - - public class TestConstructorOne implements java.io.Serializable { - public TestConstructorOne() { - } - } - - public class TestConstructorTwo implements java.io.Serializable { - public TestConstructorTwo(byte b) { - } - - public TestConstructorTwo(char c) { - } - } - - public class TestConstructorTwoReverse implements java.io.Serializable { - public TestConstructorTwoReverse(char c) { - } - - public TestConstructorTwoReverse(byte b) { - } - } - - - // Test Constructor Modifiers - public class TestConstructorPublic implements java.io.Serializable { - public TestConstructorPublic() { - } - } - - public class TestConstructorPrivate implements java.io.Serializable { - private TestConstructorPrivate() { - } - - public TestConstructorPrivate(int i) { - this(); - } - } - - public class TestConstructorProtected implements java.io.Serializable { - protected TestConstructorProtected() { - } - } - // TODO constructor modifier strict? - // TODO constructor modifier static? - // TODO constructor modifier final? - // TODO constructor modifier synchronized? - // TODO constructor modifier native? - // TODO constructor modifier abstract? - - - // Test constructor signature - public class TestConstructorSignature implements java.io.Serializable { - public TestConstructorSignature(boolean z, byte b, char c, short s, - int i, float f, double j, Object l) { - } - } - - - // Test Method Modifiers - public class TestMethodPublic implements java.io.Serializable { - public void method() { - } - } - - @SuppressWarnings("unused") - public class TestMehodPrivate implements java.io.Serializable { - private void method() { - } - } - - public class TestMethodProtected implements java.io.Serializable { - protected void method() { - } - } - - public class TestMethodStrict implements java.io.Serializable { - strictfp void method() { - } - } - - public static class TestMethodStatic implements java.io.Serializable { - static void method() { - } - } - - public class TestMethodFinal implements java.io.Serializable { - final void method() { - } - } - - public class TestMethodSynchronized implements java.io.Serializable { - synchronized void method() { - } - } - - public class TestMethodNative implements java.io.Serializable { - native void method(); - } - - public abstract class TestMethodAbstractHelper implements - java.io.Serializable { - abstract void method(); - } - - public class TestMethodAbstract extends TestMethodAbstractHelper implements - java.io.Serializable { - @Override - void method() { - } - } - - - // Test method signature - public class TestMethodSignature implements java.io.Serializable { - public void method(boolean z, byte b, char c, short s, int i, float f, - double j, Object l) { - } - } - - - // Test method return signature - public class TestMethodReturnSignature implements java.io.Serializable { - public void methodV() { - } - - public boolean methodZ() { - return false; - } - - public byte methodB() { - return 0; - } - - public char methodC() { - return '0'; - } - - public short methodS() { - return 0; - } - - public int methodI() { - return 0; - } - - public float methodF() { - return 0F; - } - - public double methodD() { - return 0D; - } - - public Object methodL() { - return null; - } - } -} diff --git a/luni/src/test/java/tests/api/java/lang/Process2Test.java b/luni/src/test/java/tests/api/java/lang/Process2Test.java deleted file mode 100644 index 5d18d61..0000000 --- a/luni/src/test/java/tests/api/java/lang/Process2Test.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.lang; - -import dalvik.annotation.AndroidOnly; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import tests.support.Support_Exec; -import static tests.support.Support_Exec.javaProcessBuilder; - -public class Process2Test extends junit.framework.TestCase { - /** - * java.lang.Process#getInputStream(), - * java.lang.Process#getErrorStream() - * java.lang.Process#getOutputStream() - * Tests if these methods return buffered streams. - */ - @AndroidOnly("dalvikvm specific") - public void test_streams() - throws IOException, InterruptedException { - Process p = javaProcessBuilder().start(); - assertNotNull(p.getInputStream()); - assertNotNull(p.getErrorStream()); - assertNotNull(p.getOutputStream()); - } - - public void test_getErrorStream() { - String[] commands = {"ls"}; - Process process = null; - try { - process = Runtime.getRuntime().exec(commands, null, null); - InputStream is = process.getErrorStream(); - StringBuffer msg = new StringBuffer(""); - while (true) { - int c = is.read(); - if (c == -1) - break; - msg.append((char) c); - } - assertEquals("", msg.toString()); - } catch (IOException e) { - fail("IOException was thrown."); - } finally { - process.destroy(); - } - - String[] unknownCommands = {"mkdir", "-u", "test"}; - Process erProcess = null; - try { - erProcess = Runtime.getRuntime().exec(unknownCommands, null, null); - InputStream is = erProcess.getErrorStream(); - StringBuffer msg = new StringBuffer(""); - while (true) { - int c = is.read(); - if (c == -1) - break; - msg.append((char) c); - } - assertTrue("Error stream should not be empty", - !"".equals(msg.toString())); - } catch (IOException e) { - fail("IOException was thrown."); - } finally { - erProcess.destroy(); - } - } -} diff --git a/luni/src/test/java/tests/api/java/lang/ProcessManagerTest.java b/luni/src/test/java/tests/api/java/lang/ProcessManagerTest.java deleted file mode 100644 index 99e1df3..0000000 --- a/luni/src/test/java/tests/api/java/lang/ProcessManagerTest.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.java.lang; - -import dalvik.annotation.BrokenTest; - -import junit.framework.TestCase; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; - -public class ProcessManagerTest extends TestCase { - - Thread thread = null; - Process process = null; - boolean isThrown = false; - - public void testCat() throws IOException, InterruptedException { - String[] commands = { "cat" }; - Process process = Runtime.getRuntime().exec(commands, null, null); - - OutputStream out = process.getOutputStream(); - String greeting = "Hello, World!"; - out.write(greeting.getBytes()); - out.write('\n'); - out.close(); - - assertEquals(greeting, readLine(process)); - } - - @BrokenTest("Sporadic failures in CTS, but not in CoreTestRunner") - public void testSleep() throws IOException { - String[] commands = { "sleep", "1" }; - process = Runtime.getRuntime().exec(commands, null, null); - try { - assertEquals(0, process.waitFor()); - - } catch(InterruptedException ie) { - fail("InterruptedException was thrown."); - } - - isThrown = false; - thread = new Thread() { - public void run() { - String[] commands = { "sleep", "1000"}; - try { - process = Runtime.getRuntime().exec(commands, null, null); - } catch (IOException e1) { - fail("IOException was thrown."); - } - try { - process.waitFor(); - fail("InterruptedException was not thrown."); - } catch(InterruptedException ie) { - isThrown = true; - } - } - }; - - Thread interruptThread = new Thread() { - public void run() { - try { - sleep(10); - } catch(InterruptedException ie) { - fail("InterruptedException was thrown in " + - "the interruptThread."); - } - thread.interrupt(); - } - }; - thread.start(); - interruptThread.start(); - try { - interruptThread.join(); - } catch (InterruptedException e) { - fail("InterruptedException was thrown."); - } - try { - Thread.sleep(100); - } catch(InterruptedException ie) { - - } - - thread.interrupt(); - //process.destroy(); - try { - Thread.sleep(100); - } catch(InterruptedException ie) { - - } - - assertTrue(isThrown); - } - - public void testPwd() throws IOException, InterruptedException { - String[] commands = { "sh", "-c", "pwd" }; - Process process = Runtime.getRuntime().exec( - commands, null, new File("/")); - logErrors(process); - assertEquals("/", readLine(process)); - } - - public void testEnvironment() throws IOException, InterruptedException { - String[] commands = { "sh", "-c", "echo $FOO" }; - - // Remember to set the path so we can find sh. - String[] environment = { "FOO=foo", "PATH=" + System.getenv("PATH") }; - Process process = Runtime.getRuntime().exec( - commands, environment, null); - logErrors(process); - assertEquals("foo", readLine(process)); - } - - String readLine(Process process) throws IOException { - InputStream in = process.getInputStream(); - BufferedReader reader = new BufferedReader(new InputStreamReader(in)); - return reader.readLine(); - } - - void logErrors(final Process process) throws IOException { - Thread thread = new Thread() { - public void run() { - InputStream in = process.getErrorStream(); - BufferedReader reader - = new BufferedReader(new InputStreamReader(in)); - String line; - try { - while ((line = reader.readLine()) != null) { - System.err.println(line); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - }; - thread.setDaemon(true); - thread.start(); - } - - public void testHeavyLoad() { - int i; - for (i = 0; i < 100; i++) - stuff(); - } - - private static void stuff() { - Runtime rt = Runtime.getRuntime(); - try { - Process proc = rt.exec("ls"); - proc.waitFor(); - proc = null; - } catch (Exception ex) { - System.err.println("Failure: " + ex); - throw new RuntimeException(ex); - } - rt.gc(); - rt = null; - } - - InputStream in; - - public void testCloseNonStandardFds() - throws IOException, InterruptedException { - String[] commands = { "ls", "/proc/self/fd" }; - - Process process = Runtime.getRuntime().exec(commands, null, null); - int before = countLines(process); - - // Open a new fd. - this.in = new FileInputStream("/proc/version"); - - try { - process = Runtime.getRuntime().exec(commands, null, null); - int after = countLines(process); - - // Assert that the new fd wasn't open in the second run. - assertEquals(before, after); - } finally { - this.in = null; - } - } - - /** - * Counts lines of input from the given process. Equivalent to "wc -l". - */ - private int countLines(Process process) throws IOException { - logErrors(process); - InputStream in = process.getInputStream(); - BufferedReader reader = new BufferedReader(new InputStreamReader(in)); - int count = 0; - while (reader.readLine() != null) { - count++; - } - return count; - } - - public void testInvalidCommand() - throws IOException, InterruptedException { - try { - String[] commands = { "doesnotexist" }; - Runtime.getRuntime().exec(commands, null, null); - } catch (IOException e) { /* expected */ } - } -} diff --git a/luni/src/test/java/tests/api/java/lang/ProcessTest.java b/luni/src/test/java/tests/api/java/lang/ProcessTest.java deleted file mode 100644 index 2a8e0bd..0000000 --- a/luni/src/test/java/tests/api/java/lang/ProcessTest.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.lang; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; - -public class ProcessTest extends junit.framework.TestCase { - - public void test_55017() throws Exception { - ArrayList<Process> children = new ArrayList<Process>(); - for (int i = 0; i < 256; ++i) { - try { - children.add(Runtime.getRuntime().exec(new String[] { "/system/bin/does-not-exist" }, null, null)); - System.gc(); - } catch (IOException expected) { - } - } - assertEquals(0, children.size()); - - boolean onDevice = new File("/system/bin").exists(); - String[] psCommand = onDevice ? new String[] { "ps" } : new String[] { "ps", "s" }; - Process ps = Runtime.getRuntime().exec(psCommand, null, null); - int zombieCount = 0; - for (String line : readAndCloseStream(ps.getInputStream()).split("\n")) { - if (line.contains(" Z ") || line.contains(" Z+ ")) { - ++zombieCount; - } - } - assertEquals(0, zombieCount); - } - - public void test_getOutputStream() throws Exception { - String[] commands = { "cat", "-"}; - Process p = Runtime.getRuntime().exec(commands, null, null); - OutputStream os = p.getOutputStream(); - // send data, and check if it is echoed back correctly - String str1 = "Some data for testing communication between processes\n"; - String str2 = "More data that serves the same purpose.\n"; - String str3 = "Here is some more data.\n"; - os.write(str1.getBytes()); - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - os.write(str2.getBytes()); - os.write(str3.getBytes()); - os.close(); - - String received = readAndCloseStream(p.getInputStream()); - assertEquals(str1 + str2 + str3, received); - - String stderr = readAndCloseStream(p.getErrorStream()); - assertEquals("", stderr); - - p.waitFor(); - p.destroy(); - } - - public void test_getErrorStream() throws Exception { - String[] commands = { "cat", "--no-such-option"}; - Process p = Runtime.getRuntime().exec(commands, null, null); - - p.getOutputStream().close(); - - String received = readAndCloseStream(p.getInputStream()); - assertEquals("", received); - - String stderr = readAndCloseStream(p.getErrorStream()); - assertTrue(stderr, stderr.contains("unrecognized option") || stderr.contains("invalid option")); - - p.waitFor(); - p.destroy(); - } - - private String readAndCloseStream(InputStream is) throws IOException { - StringBuffer result = new StringBuffer(); - while (true) { - int c = is.read(); - if (c == -1) { - break; - } - result.append((char) c); - } - is.close(); - return result.toString(); - } - - public void test_exitValue() throws Exception { - String[] commands = { "ls" }; - Process process = Runtime.getRuntime().exec(commands, null, null); - process.waitFor(); - assertEquals(0, process.exitValue()); - - String[] commandsSleep = { "sleep", "3000" }; - process = Runtime.getRuntime().exec(commandsSleep, null, null); - process.destroy(); - process.waitFor(); // destroy is asynchronous. - assertTrue(process.exitValue() != 0); - - process = Runtime.getRuntime().exec(new String[] { "sleep", "3000" }, null, null); - try { - process.exitValue(); - fail(); - } catch(IllegalThreadStateException expected) { - } - } - - public void test_destroy() throws Exception { - String[] commands = { "ls"}; - Process process = Runtime.getRuntime().exec(commands, null, null); - process.destroy(); - process.destroy(); - process.destroy(); - } -} diff --git a/luni/src/test/java/tests/api/java/lang/StringTest.java b/luni/src/test/java/tests/api/java/lang/StringTest.java deleted file mode 100644 index 1e9933d..0000000 --- a/luni/src/test/java/tests/api/java/lang/StringTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.java.lang; - -import junit.framework.TestCase; - -/** - * Tests for the class {@link String}. - */ -public class StringTest extends TestCase { - public void test_contains() { - assertTrue("aabc".contains("abc")); - assertTrue("abcd".contains("abc")); - assertFalse("abcd".contains("cba")); - } - public void test_charAt() { - assertTrue("abcd".charAt(0) == 'a'); - assertTrue("abcd".charAt(3) == 'd'); - } - public void test_StartsWith() { - assertTrue("abcd".startsWith("abc")); - assertFalse("abcd".startsWith("aabc")); - } - public void test_EndsWith() { - assertTrue("abcd".endsWith("bcd")); - assertFalse("abcd".endsWith("bcde")); - } - - public void test_CASE_INSENSITIVE_ORDER() { - String s1 = "ABCDEFG"; - String s2 = "abcdefg"; - - assertTrue(String.CASE_INSENSITIVE_ORDER.compare(s1, s2) == 0); - } -} diff --git a/luni/src/test/java/tests/api/java/lang/ref/PhantomReferenceTest.java b/luni/src/test/java/tests/api/java/lang/ref/PhantomReferenceTest.java deleted file mode 100644 index 6470579..0000000 --- a/luni/src/test/java/tests/api/java/lang/ref/PhantomReferenceTest.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.lang.ref; - -import java.lang.ref.PhantomReference; -import java.lang.ref.Reference; -import java.lang.ref.ReferenceQueue; -import libcore.java.lang.ref.FinalizationTester; - -//TODO: write a test to verify that the referent's finalize() happens -// before the PhantomReference is enqueued. - -public class PhantomReferenceTest extends junit.framework.TestCase { - static Boolean bool; - public boolean isCalled = false; - protected void doneSuite() { - bool = null; - } - - /** - * java.lang.ref.PhantomReference#get() - */ - public void test_get() { - ReferenceQueue rq = new ReferenceQueue(); - bool = new Boolean(false); - PhantomReference pr = new PhantomReference(bool, rq); - assertNull("get() should return null.", pr.get()); - pr.enqueue(); - assertNull("get() should return null.", pr.get()); - pr.clear(); - assertNull("get() should return null.", pr.get()); - } - - /** - * java.lang.Runtime#gc() - */ - public void test_gcInteraction() { - class TestPhantomReference<T> extends PhantomReference<T> { - public TestPhantomReference(T referent, - ReferenceQueue<? super T> q) { - super(referent, q); - } - public boolean enqueue() { - // Initiate another GC from inside enqueue() to - // see if it causes any problems inside the VM. - Runtime.getRuntime().gc(); - return super.enqueue(); - } - } - - final ReferenceQueue rq = new ReferenceQueue(); - final PhantomReference[] tprs = new PhantomReference[4]; - - class TestThread extends Thread { - public void run() { - // Create the object in a separate thread to ensure - // it will be gc'ed. - Object obj = new Object(); - tprs[0] = new TestPhantomReference(obj, rq); - tprs[1] = new TestPhantomReference(obj, rq); - tprs[2] = new TestPhantomReference(obj, rq); - tprs[3] = new TestPhantomReference(obj, rq); - } - } - - try { - Thread t = new TestThread(); - t.start(); - t.join(); - - FinalizationTester.induceFinalization(); - - assertNull("get() should return null.", tprs[0].get()); - assertNull("get() should return null.", tprs[1].get()); - assertNull("get() should return null.", tprs[2].get()); - assertNull("get() should return null.", tprs[3].get()); - - for (int i = 0; i < 4; i++) { - Reference r = rq.remove(100L); - assertNotNull("Reference should have been enqueued.", r); - } - - // These are to make sure that tprs and its elements don't get - // optimized out. - assertNull("get() should return null.", tprs[0].get()); - assertNull("get() should return null.", tprs[1].get()); - assertNull("get() should return null.", tprs[2].get()); - assertNull("get() should return null.", tprs[3].get()); - } catch (InterruptedException e) { - fail("InterruptedException : " + e.getMessage()); - } - } - - /** - * java.lang.ref.PhantomReference#PhantomReference(java.lang.Object, - * java.lang.ref.ReferenceQueue) - */ - public void test_ConstructorLjava_lang_ObjectLjava_lang_ref_ReferenceQueue() { - ReferenceQueue rq = new ReferenceQueue(); - bool = new Boolean(true); - try { - PhantomReference pr = new PhantomReference(bool, rq); - // Allow the finalizer to run to potentially enqueue - Thread.sleep(1000); - assertTrue("Initialization failed.", !pr.isEnqueued()); - } catch (Exception e) { - fail("Exception during test : " + e.getMessage()); - } - // need a reference to bool so the jit does not optimize it away - assertTrue("should always pass", bool.booleanValue()); - - boolean exception = false; - try { - new PhantomReference(bool, null); - } catch (NullPointerException e) { - exception = true; - } - assertTrue("Should not throw NullPointerException", !exception); - } - - protected void setUp() { - } - - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/lang/ref/ReferenceQueueTest.java b/luni/src/test/java/tests/api/java/lang/ref/ReferenceQueueTest.java deleted file mode 100644 index cad61b3..0000000 --- a/luni/src/test/java/tests/api/java/lang/ref/ReferenceQueueTest.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.lang.ref; - -import java.lang.ref.PhantomReference; -import java.lang.ref.Reference; -import java.lang.ref.ReferenceQueue; -import java.lang.ref.SoftReference; -import java.lang.ref.WeakReference; -import libcore.java.lang.ref.FinalizationTester; - -public class ReferenceQueueTest extends junit.framework.TestCase { - static Boolean b; - - static Integer integer; - boolean isThrown = false; - - protected void doneSuite() { - b = null; - integer = null; - } - - public class ChildThread implements Runnable { - public ChildThread() { - } - - public void run() { - try { - rq.wait(1000); - } catch (Exception e) { - } - synchronized (rq) { - // store in a static so it won't be gc'ed because the jit - // optimized it out - integer = new Integer(667); - SoftReference sr = new SoftReference(integer, rq); - sr.enqueue(); - rq.notify(); - } - } - } - - ReferenceQueue rq; - - /** - * java.lang.ref.ReferenceQueue#poll() - */ - public void test_poll() { - // store in a static so it won't be gc'ed because the jit - // optimized it out - b = new Boolean(true); - Object obj = new Object(); - String str = "Test"; - - SoftReference sr = new SoftReference(b, rq); - WeakReference wr = new WeakReference(obj, rq); - PhantomReference pr = new PhantomReference(str, rq); - assertNull(rq.poll()); - sr.enqueue(); - wr.enqueue(); - pr.enqueue(); - - try { - assertNull("Remove failed.", rq.poll().get()); - } catch (Exception e) { - fail("Exception during the test : " + e.getMessage()); - } - - try { - assertEquals("Remove failed.", obj, (rq.poll().get())); - } catch (Exception e) { - fail("Exception during the test : " + e.getMessage()); - } - - try { - assertTrue("Remove failed.", ((Boolean) rq.poll().get()) - .booleanValue()); - } catch (Exception e) { - fail("Exception during the test : " + e.getMessage()); - } - assertNull(rq.poll()); - - sr.enqueue(); - wr.enqueue(); - - FinalizationTester.induceFinalization(); - - assertNull(rq.poll()); - } - - /** - * java.lang.ref.ReferenceQueue#remove() - */ - public void test_remove() { - // store in a static so it won't be gc'ed because the jit - // optimized it out - b = new Boolean(true); - - SoftReference sr = new SoftReference(b, rq); - sr.enqueue(); - try { - assertTrue("Remove failed.", ((Boolean) rq.remove().get()) - .booleanValue()); - } catch (Exception e) { - fail("Exception during the test : " + e.getMessage()); - } - - assertNull(rq.poll()); - - sr.enqueue(); - - class RemoveThread extends Thread { - public void run() { - try { - rq.remove(); - } catch(InterruptedException ie) { - isThrown = true; - } - } - } - RemoveThread rt = new RemoveThread(); - rt.start(); - try { - Thread.sleep(100); - } catch(InterruptedException ie) { - - } - rt.interrupt(); - try { - Thread.sleep(100); - } catch(InterruptedException ie) { - - } - assertTrue(isThrown); - assertNull(rq.poll()); - } - - /** - * java.lang.ref.ReferenceQueue#remove(long) - */ - public void test_removeJ() { - try { - assertNull("Queue should be empty. (poll)", rq.poll()); - assertNull("Queue should be empty. (remove(1))", - rq.remove((long) 1)); - Thread ct = new Thread(new ChildThread()); - ct.start(); - Reference ret = rq.remove(0L); - assertNotNull("Delayed remove failed.", ret); - } catch (InterruptedException e) { - fail("InterruptedExeException during test : " + e.getMessage()); - } - catch (Exception e) { - fail("Exception during test : " + e.getMessage()); - } - - Object obj = new Object(); - WeakReference wr = new WeakReference(obj, rq); - Boolean b = new Boolean(true); - SoftReference sr = new SoftReference(b, rq); - String str = "Test"; - PhantomReference pr = new PhantomReference(str, rq); - - pr.enqueue(); - wr.enqueue(); - sr.enqueue(); - - try { - Reference result = rq.remove(1L); - assertTrue((Boolean)result.get()); - result = rq.remove(1L); - assertEquals(obj, result.get()); - result = rq.remove(1L); - assertNull(result.get()); - } catch (IllegalArgumentException e1) { - fail("IllegalArgumentException was thrown."); - } catch (InterruptedException e1) { - fail("InterruptedException was thrown."); - } - rq = new ReferenceQueue(); - isThrown = false; - assertNull(rq.poll()); - - class RemoveThread extends Thread { - public void run() { - try { - rq.remove(1000L); - } catch(InterruptedException ie) { - isThrown = true; - } - } - } - RemoveThread rt = new RemoveThread(); - rt.start(); - try { - Thread.sleep(10); - } catch(InterruptedException ie) { - - } - rt.interrupt(); - try { - Thread.sleep(10); - } catch(InterruptedException ie) { - - } - assertTrue(isThrown); - assertNull(rq.poll()); - - try { - rq.remove(-1); - fail("IllegalArgumentException expected."); - } catch(IllegalArgumentException iae) { - //expected - } catch (InterruptedException e) { - fail("Unexpected InterruptedException."); - } - } - - /** - * java.lang.ref.ReferenceQueue#ReferenceQueue() - */ - public void test_Constructor() { - ReferenceQueue rq = new ReferenceQueue(); - assertNull(rq.poll()); - try { - rq.remove(100L); - } catch (InterruptedException e) { - fail("InterruptedException was thrown."); - } - } - - protected void setUp() { - rq = new ReferenceQueue(); - } - - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/lang/ref/ReferenceTest.java b/luni/src/test/java/tests/api/java/lang/ref/ReferenceTest.java deleted file mode 100644 index 7461b47..0000000 --- a/luni/src/test/java/tests/api/java/lang/ref/ReferenceTest.java +++ /dev/null @@ -1,340 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.lang.ref; - -import java.lang.ref.PhantomReference; -import java.lang.ref.Reference; -import java.lang.ref.ReferenceQueue; -import java.lang.ref.SoftReference; -import java.lang.ref.WeakReference; -import junit.framework.AssertionFailedError; -import libcore.java.lang.ref.FinalizationTester; - -public class ReferenceTest extends junit.framework.TestCase { - Object tmpA, tmpB, tmpC, obj; - - volatile Reference r; - - /* - * For test_subclass(). - */ - static TestWeakReference twr; - static AssertionFailedError error; - static boolean testObjectFinalized; - static class TestWeakReference<T> extends WeakReference<T> { - public volatile boolean clearSeen = false; - public volatile boolean enqueueSeen = false; - - public TestWeakReference(T referent) { - super(referent); - } - - public TestWeakReference(T referent, ReferenceQueue<? super T> q) { - super(referent, q); - } - - public void clear() { - clearSeen = true; - if (testObjectFinalized) { - error = new AssertionFailedError("Clear should happen " + - "before finalization."); - throw error; - } - if (enqueueSeen) { - error = new AssertionFailedError("Clear should happen " + - "before enqueue."); - throw error; - } - super.clear(); - } - - public boolean enqueue() { - enqueueSeen = true; - if (!clearSeen) { - error = new AssertionFailedError("Clear should happen " + - "before enqueue."); - throw error; - } - - /* Do this last; it may notify the main test thread, - * and anything we'd do after it (e.g., setting clearSeen) - * wouldn't be seen. - */ - return super.enqueue(); - } - } - - protected void doneSuite() { - tmpA = tmpB = obj = null; - } - - /** - * java.lang.ref.Reference#clear() - */ - public void test_clear() { - tmpA = new Object(); - tmpB = new Object(); - tmpC = new Object(); - SoftReference sr = new SoftReference(tmpA, new ReferenceQueue()); - WeakReference wr = new WeakReference(tmpB, new ReferenceQueue()); - PhantomReference pr = new PhantomReference(tmpC, new ReferenceQueue()); - assertTrue("Start: Object not cleared.", (sr.get() != null) - && (wr.get() != null)); - assertNull("Referent is not null.", pr.get()); - sr.clear(); - wr.clear(); - pr.clear(); - assertTrue("End: Object cleared.", (sr.get() == null) - && (wr.get() == null)); - assertNull("Referent is not null.", pr.get()); - // Must reference tmpA and tmpB so the jit does not optimize them away - assertTrue("should always pass", tmpA != sr.get() && tmpB != wr.get()); - } - - /** - * java.lang.ref.Reference#enqueue() - */ - public void test_enqueue() { - ReferenceQueue rq = new ReferenceQueue(); - obj = new Object(); - Reference ref = new SoftReference(obj, rq); - assertTrue("Enqueue failed.", (!ref.isEnqueued()) - && ((ref.enqueue()) && (ref.isEnqueued()))); - assertTrue("Not properly enqueued.", rq.poll().get() == obj); - // This fails... - assertTrue("Should remain enqueued.", !ref.isEnqueued()); - assertTrue("Can not enqueue twice.", (!ref.enqueue()) - && (rq.poll() == null)); - - rq = new ReferenceQueue(); - obj = new Object(); - - ref = new WeakReference(obj, rq); - assertTrue("Enqueue failed2.", (!ref.isEnqueued()) - && ((ref.enqueue()) && (ref.isEnqueued()))); - assertTrue("Not properly enqueued2.", rq.poll().get() == obj); - assertTrue("Should remain enqueued2.", !ref.isEnqueued()); // This - // fails. - assertTrue("Can not enqueue twice2.", (!ref.enqueue()) - && (rq.poll() == null)); - - ref = new PhantomReference(obj, rq); - assertTrue("Enqueue failed3.", (!ref.isEnqueued()) - && ((ref.enqueue()) && (ref.isEnqueued()))); - assertNull("Not properly enqueued3.", rq.poll().get()); - assertTrue("Should remain enqueued3.", !ref.isEnqueued()); // This - // fails. - assertTrue("Can not enqueue twice3.", (!ref.enqueue()) - && (rq.poll() == null)); - } - - public void test_get_WeakReference() throws Exception { - // Test the general/overall functionality of Reference. - ReferenceQueue<Object> queue = new ReferenceQueue<Object>(); - - r = newWeakReference(queue); - FinalizationTester.induceFinalization(); - Reference ref = queue.remove(); - assertNotNull("Object not enqueued.", ref); - assertSame("Unexpected ref1", ref, r); - assertNull("Object could not be reclaimed1.", r.get()); - - r = newWeakReference(queue); - FinalizationTester.induceFinalization(); - - // wait for the reference queue thread to enqueue the newly-finalized object - Thread.yield(); - Thread.sleep(200); - - ref = queue.poll(); - assertNotNull("Object not enqueued.", ref); - assertSame("Unexpected ref2", ref, r); - assertNull("Object could not be reclaimed.", ref.get()); - assertNull("Object could not be reclaimed.", r.get()); - } - - /** - * Makes sure that overridden versions of clear() and enqueue() - * get called, and that clear/enqueue/finalize happen in the - * right order for WeakReferences. - * - * java.lang.ref.Reference#clear() - * java.lang.ref.Reference#enqueue() - * java.lang.Object#finalize() - */ - public void test_subclass() { - error = null; - testObjectFinalized = false; - twr = null; - - class TestObject { - public TestWeakReference testWeakReference = null; - - public void setTestWeakReference(TestWeakReference twr) { - testWeakReference = twr; - } - - protected void finalize() { - testObjectFinalized = true; - } - } - - final ReferenceQueue rq = new ReferenceQueue(); - - class TestThread extends Thread { - public void run() { - // Create the object in a separate thread to ensure it will be - // gc'ed - TestObject testObj = new TestObject(); - twr = new TestWeakReference(testObj, rq); - testObj.setTestWeakReference(twr); - testObj = null; - } - } - - Reference ref; - - try { - Thread t = new TestThread(); - t.start(); - t.join(); - FinalizationTester.induceFinalization(); - ref = rq.remove(5000L); // Give up after five seconds. - - assertNotNull("Object not garbage collected.", ref); - assertTrue("Unexpected reference.", ref == twr); - assertNull("Object could not be reclaimed.", twr.get()); - //assertTrue("Overridden clear() should have been called.", - // twr.clearSeen); - //assertTrue("Overridden enqueue() should have been called.", - // twr.enqueueSeen); - assertTrue("finalize() should have been called.", - testObjectFinalized); - } catch (InterruptedException e) { - fail("InterruptedException : " + e.getMessage()); - } - - } - - /** - * java.lang.ref.Reference#get() - */ - public void test_get() { - WeakReference ref = newWeakReference(null); - - FinalizationTester.induceFinalization(); - assertNull("get() doesn't return null after gc for WeakReference", ref.get()); - - obj = new Object(); - ref = new WeakReference<Object>(obj, new ReferenceQueue<Object>()); - ref.clear(); - assertNull("get() doesn't return null after clear for WeakReference", ref.get()); - } - - /** - * Helper method to prevent live-precise bugs from interfering with analysis - * of what is reachable. Do not inline this method; otherwise tests may fail - * on VMs that are not live-precise. http://b/4191345 - */ - private WeakReference<Object> newWeakReference(ReferenceQueue<Object> queue) { - Object o = new Object(); - WeakReference<Object> ref = new WeakReference<Object>(o, queue); - assertSame(o, ref.get()); - return ref; - } - - /** - * java.lang.ref.Reference#isEnqueued() - */ - public void test_isEnqueued() { - ReferenceQueue rq = new ReferenceQueue(); - obj = new Object(); - Reference ref = new SoftReference(obj, rq); - assertTrue("Should start off not enqueued.", !ref.isEnqueued()); - ref.enqueue(); - assertTrue("Should now be enqueued.", ref.isEnqueued()); - ref.enqueue(); - assertTrue("Should still be enqueued.", ref.isEnqueued()); - rq.poll(); - // This fails ... - assertTrue("Should now be not enqueued.", !ref.isEnqueued()); - } - - /* Contrives a situation where the only reference to a string - * is a WeakReference from an object that is being finalized. - * Checks to make sure that the referent of the WeakReference - * is still pointing to a valid object. - */ - public void test_finalizeReferenceInteraction() { - error = null; - testObjectFinalized = false; - - class TestObject { - WeakReference<String> stringRef; - - public TestObject(String referent) { - stringRef = new WeakReference<String>(referent); - } - - protected void finalize() { - try { - /* If a VM bug has caused the referent to get - * freed without the reference getting cleared, - * looking it up, assigning it to a local and - * doing a GC should cause some sort of exception. - */ - String s = stringRef.get(); - System.gc(); - testObjectFinalized = true; - } catch (Throwable t) { - error = new AssertionFailedError("something threw '" + t + - "' in finalize()"); - } - } - } - - class TestThread extends Thread { - public void run() { - // Create the object in a separate thread to ensure it will be - // gc'ed - TestObject testObj = new TestObject(new String("sup /b/")); - } - } - - try { - Thread t = new TestThread(); - t.start(); - t.join(); - FinalizationTester.induceFinalization(); - Thread.sleep(1000); - if (error != null) { - throw error; - } - assertTrue("finalize() should have been called.", - testObjectFinalized); - } catch (InterruptedException e) { - fail("InterruptedException : " + e.getMessage()); - } - } - - - protected void setUp() { - } - - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/lang/ref/SoftReferenceTest.java b/luni/src/test/java/tests/api/java/lang/ref/SoftReferenceTest.java deleted file mode 100644 index 197d829..0000000 --- a/luni/src/test/java/tests/api/java/lang/ref/SoftReferenceTest.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.lang.ref; - -import dalvik.annotation.SideEffect; - -import java.lang.ref.Reference; -import java.lang.ref.ReferenceQueue; -import java.lang.ref.SoftReference; -import java.util.Vector; -import libcore.java.lang.ref.FinalizationTester; - -public class SoftReferenceTest extends junit.framework.TestCase { - static Boolean bool; - SoftReference r; - - protected void doneSuite() { - bool = null; - } - - /** - * java.lang.ref.SoftReference#SoftReference(java.lang.Object, - * java.lang.ref.ReferenceQueue) - */ - public void test_ConstructorLjava_lang_ObjectLjava_lang_ref_ReferenceQueue() { - ReferenceQueue rq = new ReferenceQueue(); - bool = new Boolean(true); - try { - SoftReference sr = new SoftReference(bool, rq); - assertTrue("Initialization failed.", ((Boolean) sr.get()) - .booleanValue()); - } catch (Exception e) { - fail("Exception during test : " + e.getMessage()); - } - - boolean exception = false; - try { - new SoftReference(bool, null); - } catch (NullPointerException e) { - exception = true; - } - assertTrue("Should not throw NullPointerException", !exception); - } - - /** - * java.lang.ref.SoftReference#SoftReference(java.lang.Object) - */ - public void test_ConstructorLjava_lang_Object() { - bool = new Boolean(true); - try { - SoftReference sr = new SoftReference(bool); - assertTrue("Initialization failed.", ((Boolean) sr.get()) - .booleanValue()); - } catch (Exception e) { - fail("Exception during test : " + e.getMessage()); - } - } - - /** - * java.lang.ref.SoftReference#get() - */ - public void test_get() { - bool = new Boolean(false); - SoftReference sr = new SoftReference(bool); - assertTrue("Same object not returned.", bool == sr.get()); - } - - @SideEffect("Causes OutOfMemoryError to test finalization") - public void test_get_SoftReference() { - - class TestObject { - public boolean finalized; - public TestObject() { - finalized = false; - } - - protected void finalize() { - finalized = true; - } - } - - final ReferenceQueue rq = new ReferenceQueue(); - - class TestThread extends Thread { - public void run() { - Object testObj = new TestObject(); - r = new SoftReference(testObj, rq); - } - } - Reference ref; - try { - TestThread t = new TestThread(); - t.start(); - t.join(); - Vector<StringBuffer> v = new Vector<StringBuffer>(); - try { - while(true) { - v.add(new StringBuffer(10000)); - } - } catch(OutOfMemoryError ofme) { - v = null; - } - } catch (InterruptedException e) { - fail("InterruptedException : " + e.getMessage()); - } - - assertNull("get() should return null " + - "if OutOfMemoryError is thrown.", r.get()); - - try { - TestThread t = new TestThread(); - t.start(); - t.join(); - FinalizationTester.induceFinalization(); - ref = rq.poll(); - assertNotNull("Object not garbage collected.", ref); - assertNull("Object is not null.", ref.get()); - assertNotNull("Object could not be reclaimed.", r.get()); - } catch (Exception e) { - fail("Exception : " + e.getMessage()); - } - } - - protected void setUp() { - } - - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/lang/ref/WeakReferenceTest.java b/luni/src/test/java/tests/api/java/lang/ref/WeakReferenceTest.java deleted file mode 100644 index 2bddc1b..0000000 --- a/luni/src/test/java/tests/api/java/lang/ref/WeakReferenceTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.lang.ref; - -import java.lang.ref.ReferenceQueue; -import java.lang.ref.WeakReference; - -public class WeakReferenceTest extends junit.framework.TestCase { - static Boolean bool; - - protected void doneSuite() { - bool = null; - } - - /** - * java.lang.ref.WeakReference#WeakReference(java.lang.Object, - * java.lang.ref.ReferenceQueue) - */ - public void test_ConstructorLjava_lang_ObjectLjava_lang_ref_ReferenceQueue() { - ReferenceQueue rq = new ReferenceQueue(); - bool = new Boolean(true); - try { - // Allow the finalizer to run to potentially enqueue - WeakReference wr = new WeakReference(bool, rq); - assertTrue("Initialization failed.", ((Boolean) wr.get()) - .booleanValue()); - } catch (Exception e) { - fail("Exception during test : " + e.getMessage()); - } - // need a reference to bool so the jit does not optimize it away - assertTrue("should always pass", bool.booleanValue()); - - boolean exception = false; - try { - new WeakReference(bool, null); - } catch (NullPointerException e) { - exception = true; - } - assertTrue("Should not throw NullPointerException", !exception); - } - - /** - * java.lang.ref.WeakReference#WeakReference(java.lang.Object) - */ - public void test_ConstructorLjava_lang_Object() { - bool = new Boolean(true); - try { - WeakReference wr = new WeakReference(bool); - // Allow the finalizer to run to potentially enqueue - Thread.sleep(1000); - assertTrue("Initialization failed.", ((Boolean) wr.get()) - .booleanValue()); - } catch (Exception e) { - fail("Exception during test : " + e.getMessage()); - } - // need a reference to bool so the jit does not optimize it away - assertTrue("should always pass", bool.booleanValue()); - } - - protected void setUp() { - } - - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/lang/reflect/AccessibleObjectTest.java b/luni/src/test/java/tests/api/java/lang/reflect/AccessibleObjectTest.java deleted file mode 100644 index 41c9798..0000000 --- a/luni/src/test/java/tests/api/java/lang/reflect/AccessibleObjectTest.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.lang.reflect; - -import java.lang.annotation.Annotation; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.lang.reflect.AccessibleObject; -import java.lang.reflect.Modifier; -import java.util.HashSet; -import java.util.Set; - -public class AccessibleObjectTest extends junit.framework.TestCase { - - public class TestClass { - public Object aField; - - @InheritedRuntime - public void annotatedMethod(){} - } - - public class SubTestClass extends TestClass{ - @AnnotationRuntime0 - @AnnotationRuntime1 - @AnnotationClass0 - @AnnotationSource0 - public void annotatedMethod(){} - } - - - @Retention(RetentionPolicy.RUNTIME) - @Target( {ElementType.METHOD}) - static @interface AnnotationRuntime0 { - } - - @Retention(RetentionPolicy.RUNTIME) - @Target( { ElementType.METHOD}) - static @interface AnnotationRuntime1 { - } - - @Retention(RetentionPolicy.CLASS) - @Target( { ElementType.METHOD}) - static @interface AnnotationClass0 { - } - - @Retention(RetentionPolicy.SOURCE) - @Target( {ElementType.METHOD}) - static @interface AnnotationSource0 { - } - - @Inherited - @Retention(RetentionPolicy.RUNTIME) - @Target( {ElementType.METHOD}) - static @interface InheritedRuntime { - } - - //used for constructor test - private static class MyAccessibleObject extends AccessibleObject{ - public MyAccessibleObject() { - super(); - } - } - - /** - * java.lang.reflect.AccessibleObject#AccessibleObject() - */ - public void test_Constructor() { - assertNotNull(new MyAccessibleObject()); - } - - /** - * java.lang.reflect.AccessibleObject#isAccessible() - */ - public void test_isAccessible() { - // Test for method boolean - // java.lang.reflect.AccessibleObject.isAccessible() - try { - AccessibleObject ao = TestClass.class.getField("aField"); - ao.setAccessible(true); - assertTrue("Returned false to isAccessible", ao.isAccessible()); - ao.setAccessible(false); - assertTrue("Returned true to isAccessible", !ao.isAccessible()); - } catch (Exception e) { - fail("Exception during test : " + e.getMessage()); - } - } - - /** - * java.lang.reflect.AccessibleObject#setAccessible(java.lang.reflect.AccessibleObject[], - * boolean) - */ - public void test_setAccessible$Ljava_lang_reflect_AccessibleObjectZ() { - try { - AccessibleObject ao = TestClass.class.getField("aField"); - AccessibleObject[] aoa = new AccessibleObject[] { ao }; - AccessibleObject.setAccessible(aoa, true); - assertTrue("Returned false to isAccessible", ao.isAccessible()); - AccessibleObject.setAccessible(aoa, false); - assertTrue("Returned true to isAccessible", !ao.isAccessible()); - } catch (Exception e) { - fail("Exception during test : " + e.getMessage()); - } - } - - /** - * java.lang.reflect.AccessibleObject#setAccessible(boolean) - */ - public void test_setAccessible() throws Exception { - AccessibleObject ao = TestClass.class.getField("aField"); - ao.setAccessible(true); - assertTrue("Returned false to isAccessible", ao.isAccessible()); - ao.setAccessible(false); - assertFalse("Returned true to isAccessible", ao.isAccessible()); - } - - public void test_getAnnotation() throws Exception{ - AccessibleObject ao = SubTestClass.class.getMethod("annotatedMethod"); - //test error case - boolean npeThrown = false; - try { - ao.getAnnotation(null); - fail("NPE expected"); - } catch (NullPointerException e) { - npeThrown = true; - } - assertTrue("NPE expected", npeThrown); - - //test inherited on method has no effect - InheritedRuntime ir = ao.getAnnotation(InheritedRuntime.class); - assertNull("Inherited Annotations should have no effect", ir); - - //test ordinary runtime annotation - AnnotationRuntime0 rt0 = ao.getAnnotation(AnnotationRuntime0.class); - assertNotNull("AnnotationRuntime0 instance expected", rt0); - } - - public void test_getAnnotations() throws Exception { - AccessibleObject ao = SubTestClass.class.getMethod("annotatedMethod"); - Annotation[] annotations = ao.getAnnotations(); - assertEquals(2, annotations.length); - - Set<Class<?>> ignoreOrder = new HashSet<Class<?>>(); - ignoreOrder.add(annotations[0].annotationType()); - ignoreOrder.add(annotations[1].annotationType()); - - assertTrue("Missing @AnnotationRuntime0", - ignoreOrder.contains(AnnotationRuntime0.class)); - assertTrue("Missing @AnnotationRuntime1", - ignoreOrder.contains(AnnotationRuntime1.class)); - } - - public void test_getDeclaredAnnotations() throws Exception { - AccessibleObject ao = SubTestClass.class.getMethod("annotatedMethod"); - Annotation[] annotations = ao.getDeclaredAnnotations(); - assertEquals(2, annotations.length); - - Set<Class<?>> ignoreOrder = new HashSet<Class<?>>(); - ignoreOrder.add(annotations[0].annotationType()); - ignoreOrder.add(annotations[1].annotationType()); - - assertTrue("Missing @AnnotationRuntime0", - ignoreOrder.contains(AnnotationRuntime0.class)); - assertTrue("Missing @AnnotationRuntime1", - ignoreOrder.contains(AnnotationRuntime1.class)); - } - - public void test_isAnnotationPresent() throws Exception { - AccessibleObject ao = SubTestClass.class.getMethod("annotatedMethod"); - assertTrue("Missing @AnnotationRuntime0", - ao.isAnnotationPresent(AnnotationRuntime0.class)); - assertFalse("AnnotationSource0 should not be visible at runtime", - ao.isAnnotationPresent(AnnotationSource0.class)); - boolean npeThrown = false; - try { - ao.isAnnotationPresent(null); - fail("NPE expected"); - } catch (NullPointerException e) { - npeThrown = true; - } - assertTrue("NPE expected", npeThrown); - } - - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/lang/reflect/ArrayTest.java b/luni/src/test/java/tests/api/java/lang/reflect/ArrayTest.java deleted file mode 100644 index d9e05fb..0000000 --- a/luni/src/test/java/tests/api/java/lang/reflect/ArrayTest.java +++ /dev/null @@ -1,1001 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.lang.reflect; - -import java.lang.reflect.Array; - -public class ArrayTest extends junit.framework.TestCase { - - /** - * java.lang.reflect.Array#get(java.lang.Object, int) - */ - public void test_getLjava_lang_ObjectI() { - // Test for method java.lang.Object - // java.lang.reflect.Array.get(java.lang.Object, int) - - int[] x = { 1 }; - Object ret = null; - boolean thrown = false; - try { - ret = Array.get(x, 0); - } catch (Exception e) { - fail("Exception during get test : " + e.getMessage()); - } - assertEquals("Get returned incorrect value", - 1, ((Integer) ret).intValue()); - try { - ret = Array.get(new Object(), 0); - } catch (IllegalArgumentException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Passing non-array failed to throw exception"); - } - thrown = false; - try { - ret = Array.get(x, 4); - } catch (ArrayIndexOutOfBoundsException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Invalid index failed to throw exception"); - } - - //same test with non primitive component type - Integer[] y = new Integer[]{ 1 }; - ret = null; - thrown = false; - try { - ret = Array.get(y, 0); - } catch (Exception e) { - fail("Exception during get test : " + e.getMessage()); - } - assertEquals("Get returned incorrect value", - 1, ((Integer) ret).intValue()); - try { - ret = Array.get(new Object(), 0); - } catch (IllegalArgumentException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Passing non-array failed to throw exception"); - } - thrown = false; - try { - ret = Array.get(y, 4); - } catch (ArrayIndexOutOfBoundsException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Invalid index failed to throw exception"); - } - } - - /** - * java.lang.reflect.Array#getBoolean(java.lang.Object, int) - */ - public void test_getBooleanLjava_lang_ObjectI() { - // Test for method boolean - // java.lang.reflect.Array.getBoolean(java.lang.Object, int) - boolean[] x = { true }; - boolean ret = false; - boolean thrown = false; - try { - ret = Array.getBoolean(x, 0); - } catch (Exception e) { - fail("Exception during get test : " + e.getMessage()); - } - assertTrue("Get returned incorrect value", ret); - try { - ret = Array.getBoolean(new Object(), 0); - } catch (IllegalArgumentException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Passing non-array failed to throw exception"); - } - thrown = false; - try { - ret = Array.getBoolean(x, 4); - } catch (ArrayIndexOutOfBoundsException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Invalid index failed to throw exception"); - } - thrown = false; - try { - ret = Array.getBoolean(null, 0); - } catch (NullPointerException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Null argument failed to throw NPE"); - } - } - - /** - * java.lang.reflect.Array#getByte(java.lang.Object, int) - */ - public void test_getByteLjava_lang_ObjectI() { - // Test for method byte - // java.lang.reflect.Array.getByte(java.lang.Object, int) - byte[] x = { 1 }; - byte ret = 0; - boolean thrown = false; - try { - ret = Array.getByte(x, 0); - } catch (Exception e) { - fail("Exception during get test : " + e.getMessage()); - } - assertEquals("Get returned incorrect value", 1, ret); - try { - ret = Array.getByte(new Object(), 0); - } catch (IllegalArgumentException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Passing non-array failed to throw exception"); - } - thrown = false; - try { - ret = Array.getByte(x, 4); - } catch (ArrayIndexOutOfBoundsException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Invalid index failed to throw exception"); - } - thrown = false; - try { - ret = Array.getByte(null, 0); - } catch (NullPointerException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Null argument failed to throw NPE"); - } - } - - /** - * java.lang.reflect.Array#getChar(java.lang.Object, int) - */ - public void test_getCharLjava_lang_ObjectI() { - // Test for method char - // java.lang.reflect.Array.getChar(java.lang.Object, int) - char[] x = { 1 }; - char ret = 0; - boolean thrown = false; - try { - ret = Array.getChar(x, 0); - } catch (Exception e) { - fail("Exception during get test : " + e.getMessage()); - } - assertEquals("Get returned incorrect value", 1, ret); - try { - ret = Array.getChar(new Object(), 0); - } catch (IllegalArgumentException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Passing non-array failed to throw exception"); - } - thrown = false; - try { - ret = Array.getChar(x, 4); - } catch (ArrayIndexOutOfBoundsException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Invalid index failed to throw exception"); - } - thrown = false; - try { - ret = Array.getChar(null, 0); - } catch (NullPointerException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Null argument failed to throw NPE"); - } - } - - /** - * java.lang.reflect.Array#getDouble(java.lang.Object, int) - */ - public void test_getDoubleLjava_lang_ObjectI() { - // Test for method double - // java.lang.reflect.Array.getDouble(java.lang.Object, int) - double[] x = { 1 }; - double ret = 0; - boolean thrown = false; - try { - ret = Array.getDouble(x, 0); - } catch (Exception e) { - fail("Exception during get test : " + e.getMessage()); - } - assertEquals("Get returned incorrect value", 1, ret, 0.0); - try { - ret = Array.getDouble(new Object(), 0); - } catch (IllegalArgumentException e) { - // Correct behaviour - thrown = true; - } - - if (!thrown) { - fail("Passing non-array failed to throw exception"); - } - thrown = false; - try { - ret = Array.getDouble(x, 4); - } catch (ArrayIndexOutOfBoundsException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Invalid index failed to throw exception"); - } - thrown = false; - try { - ret = Array.getDouble(null, 0); - } catch (NullPointerException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Null argument failed to throw NPE"); - } - } - - /** - * java.lang.reflect.Array#getFloat(java.lang.Object, int) - */ - public void test_getFloatLjava_lang_ObjectI() { - // Test for method float - // java.lang.reflect.Array.getFloat(java.lang.Object, int) - float[] x = { 1 }; - float ret = 0; - boolean thrown = false; - try { - ret = Array.getFloat(x, 0); - } catch (Exception e) { - fail("Exception during get test : " + e.getMessage()); - } - assertEquals("Get returned incorrect value", 1, ret, 0.0); - try { - ret = Array.getFloat(new Object(), 0); - } catch (IllegalArgumentException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Passing non-array failed to throw exception"); - } - thrown = false; - try { - ret = Array.getFloat(x, 4); - } catch (ArrayIndexOutOfBoundsException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Invalid index failed to throw exception"); - } - thrown = false; - try { - ret = Array.getFloat(null, 0); - } catch (NullPointerException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Null argument failed to throw NPE"); - } - } - - /** - * java.lang.reflect.Array#getInt(java.lang.Object, int) - */ - public void test_getIntLjava_lang_ObjectI() { - // Test for method int java.lang.reflect.Array.getInt(java.lang.Object, - // int) - int[] x = { 1 }; - int ret = 0; - boolean thrown = false; - try { - ret = Array.getInt(x, 0); - } catch (Exception e) { - fail("Exception during get test : " + e.getMessage()); - } - assertEquals("Get returned incorrect value", 1, ret); - try { - ret = Array.getInt(new Object(), 0); - } catch (IllegalArgumentException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Passing non-array failed to throw exception"); - } - thrown = false; - try { - ret = Array.getInt(x, 4); - } catch (ArrayIndexOutOfBoundsException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Invalid index failed to throw exception"); - } - thrown = false; - try { - ret = Array.getInt(null, 0); - } catch (NullPointerException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Null argument failed to throw NPE"); - } - } - - /** - * java.lang.reflect.Array#getLength(java.lang.Object) - */ - public void test_getLengthLjava_lang_Object() { - // Test for method int - // java.lang.reflect.Array.getLength(java.lang.Object) - long[] x = { 1 }; - - assertEquals("Returned incorrect length", 1, Array.getLength(x)); - assertEquals("Returned incorrect length", 10000, Array - .getLength(new Object[10000])); - try { - Array.getLength(new Object()); - } catch (IllegalArgumentException e) { - // Correct - return; - } - fail("Failed to throw exception when passed non-array"); - } - - /** - * java.lang.reflect.Array#getLong(java.lang.Object, int) - */ - public void test_getLongLjava_lang_ObjectI() { - // Test for method long - // java.lang.reflect.Array.getLong(java.lang.Object, int) - long[] x = { 1 }; - long ret = 0; - boolean thrown = false; - try { - ret = Array.getLong(x, 0); - } catch (Exception e) { - fail("Exception during get test : " + e.getMessage()); - } - assertEquals("Get returned incorrect value", 1, ret); - try { - ret = Array.getLong(new Object(), 0); - } catch (IllegalArgumentException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Passing non-array failed to throw exception"); - } - thrown = false; - try { - ret = Array.getLong(x, 4); - } catch (ArrayIndexOutOfBoundsException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Invalid index failed to throw exception"); - } - thrown = false; - try { - ret = Array.getLong(null, 0); - } catch (NullPointerException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Null argument failed to throw NPE"); - } - } - - /** - * java.lang.reflect.Array#getShort(java.lang.Object, int) - */ - public void test_getShortLjava_lang_ObjectI() { - // Test for method short - // java.lang.reflect.Array.getShort(java.lang.Object, int) - short[] x = { 1 }; - short ret = 0; - boolean thrown = false; - try { - ret = Array.getShort(x, 0); - } catch (Exception e) { - fail("Exception during get test : " + e.getMessage()); - } - assertEquals("Get returned incorrect value", 1, ret); - try { - ret = Array.getShort(new Object(), 0); - } catch (IllegalArgumentException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Passing non-array failed to throw exception"); - } - thrown = false; - try { - ret = Array.getShort(x, 4); - } catch (ArrayIndexOutOfBoundsException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Invalid index failed to throw exception"); - } - thrown = false; - try { - ret = Array.getShort(null, 0); - } catch (NullPointerException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Null argument failed to throw NPE"); - } - } - - /** - * java.lang.reflect.Array#newInstance(java.lang.Class, int[]) - */ - public void test_newInstanceLjava_lang_Class$I() { - // Test for method java.lang.Object - // java.lang.reflect.Array.newInstance(java.lang.Class, int []) - int[][] x; - int[] y = { 2 }; - - x = (int[][]) Array.newInstance(int[].class, y); - assertEquals("Failed to instantiate array properly", 2, x.length); - - boolean thrown = false; - try { - x = (int[][]) Array.newInstance(null, y); - } catch (NullPointerException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Null argument failed to throw NPE"); - } - - thrown = false; - try { - Array.newInstance(int[].class, new int[]{1,-1}); - } catch (NegativeArraySizeException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Negative array size failed to throw NegativeArraySizeException"); - } - - thrown = false; - try { - Array.newInstance(int[].class, new int[]{}); - } catch (IllegalArgumentException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Zero array size failed to throw IllegalArgumentException"); - } - } - - /** - * java.lang.reflect.Array#newInstance(java.lang.Class, int) - */ - public void test_newInstanceLjava_lang_ClassI() { - // Test for method java.lang.Object - // java.lang.reflect.Array.newInstance(java.lang.Class, int) - int[] x; - - x = (int[]) Array.newInstance(int.class, 100); - assertEquals("Failed to instantiate array properly", 100, x.length); - - boolean thrown = false; - try { - Array.newInstance(null, 100); - } catch (NullPointerException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Null argument failed to throw NPE"); - } - - thrown = false; - try { - Array.newInstance(int[].class, -1); - } catch (NegativeArraySizeException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Negative array size failed to throw NegativeArraySizeException"); - } - } - - /** - * java.lang.reflect.Array#set(java.lang.Object, int, - * java.lang.Object) - */ - public void test_setLjava_lang_ObjectILjava_lang_Object() { - // Test for method void java.lang.reflect.Array.set(java.lang.Object, - // int, java.lang.Object) - int[] x = { 0 }; - boolean thrown = false; - try { - Array.set(x, 0, new Integer(1)); - } catch (Exception e) { - fail("Exception during get test : " + e.getMessage()); - } - assertEquals("Get returned incorrect value", 1, ((Integer) Array.get(x, 0)) - .intValue()); - try { - Array.set(new Object(), 0, new Object()); - } catch (IllegalArgumentException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Passing non-array failed to throw exception"); - } - thrown = false; - try { - Array.set(x, 4, new Integer(1)); - } catch (ArrayIndexOutOfBoundsException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Invalid index failed to throw exception"); - } - - // trying to put null in a primitive array causes - // a IllegalArgumentException in 5.0 - boolean exception = false; - try { - Array.set(new int[1], 0, null); - } catch (IllegalArgumentException e) { - exception = true; - } - assertTrue("expected exception not thrown", exception); - - thrown = false; - try { - Array.set(null, 0, 2); - } catch (NullPointerException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Null argument failed to throw NPE"); - } - } - - /** - * java.lang.reflect.Array#setBoolean(java.lang.Object, int, boolean) - */ - public void test_setBooleanLjava_lang_ObjectIZ() { - // Test for method void - // java.lang.reflect.Array.setBoolean(java.lang.Object, int, boolean) - boolean[] x = { false }; - boolean thrown = false; - try { - Array.setBoolean(x, 0, true); - } catch (Exception e) { - fail("Exception during get test : " + e.getMessage()); - } - assertTrue("Failed to set correct value", Array.getBoolean(x, 0)); - try { - Array.setBoolean(new Object(), 0, false); - } catch (IllegalArgumentException e) { - // Correct behaviour - thrown = true; - } - if (!thrown){ - fail("Passing non-array failed to throw exception"); - } - thrown = false; - try { - Array.setBoolean(x, 4, false); - } catch (ArrayIndexOutOfBoundsException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Invalid index failed to throw exception"); - } - - thrown = false; - try { - Array.setBoolean(null, 0, true); - } catch (NullPointerException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Null argument failed to throw NPE"); - } - } - - /** - * java.lang.reflect.Array#setByte(java.lang.Object, int, byte) - */ - public void test_setByteLjava_lang_ObjectIB() { - // Test for method void - // java.lang.reflect.Array.setByte(java.lang.Object, int, byte) - byte[] x = { 0 }; - boolean thrown = false; - try { - Array.setByte(x, 0, (byte) 1); - } catch (Exception e) { - fail("Exception during get test : " + e.getMessage()); - } - assertEquals("Get returned incorrect value", 1, Array.getByte(x, 0)); - try { - Array.setByte(new Object(), 0, (byte) 9); - } catch (IllegalArgumentException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Passing non-array failed to throw exception"); - } - thrown = false; - try { - Array.setByte(x, 4, (byte) 9); - } catch (ArrayIndexOutOfBoundsException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Invalid index failed to throw exception"); - } - - thrown = false; - try { - Array.setByte(null, 0, (byte)0); - } catch (NullPointerException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Null argument failed to throw NPE"); - } - } - - /** - * java.lang.reflect.Array#setChar(java.lang.Object, int, char) - */ - public void test_setCharLjava_lang_ObjectIC() { - // Test for method void - // java.lang.reflect.Array.setChar(java.lang.Object, int, char) - char[] x = { 0 }; - boolean thrown = false; - try { - Array.setChar(x, 0, (char) 1); - } catch (Exception e) { - fail("Exception during get test : " + e.getMessage()); - } - assertEquals("Get returned incorrect value", 1, Array.getChar(x, 0)); - try { - Array.setChar(new Object(), 0, (char) 9); - } catch (IllegalArgumentException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Passing non-array failed to throw exception"); - } - thrown = false; - try { - Array.setChar(x, 4, (char) 9); - } catch (ArrayIndexOutOfBoundsException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Invalid index failed to throw exception"); - } - - thrown = false; - try { - Array.setChar(null, 0, (char)0); - } catch (NullPointerException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Null argument failed to throw NPE"); - } - } - - /** - * java.lang.reflect.Array#setDouble(java.lang.Object, int, double) - */ - public void test_setDoubleLjava_lang_ObjectID() { - // Test for method void - // java.lang.reflect.Array.setDouble(java.lang.Object, int, double) - double[] x = { 0 }; - boolean thrown = false; - try { - Array.setDouble(x, 0, 1); - } catch (Exception e) { - fail("Exception during get test : " + e.getMessage()); - } - assertEquals("Get returned incorrect value", 1, Array.getDouble(x, 0), 0.0); - try { - Array.setDouble(new Object(), 0, 9); - } catch (IllegalArgumentException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Passing non-array failed to throw exception"); - } - thrown = false; - try { - Array.setDouble(x, 4, 9); - } catch (ArrayIndexOutOfBoundsException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Invalid index failed to throw exception"); - } - - thrown = false; - try { - Array.setDouble(null, 0, 0); - } catch (NullPointerException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Null argument failed to throw NPE"); - } - } - - /** - * java.lang.reflect.Array#setFloat(java.lang.Object, int, float) - */ - public void test_setFloatLjava_lang_ObjectIF() { - // Test for method void - // java.lang.reflect.Array.setFloat(java.lang.Object, int, float) - float[] x = { 0.0f }; - boolean thrown = false; - try { - Array.setFloat(x, 0, (float) 1); - } catch (Exception e) { - fail("Exception during get test : " + e.getMessage()); - } - assertEquals("Get returned incorrect value", 1, Array.getFloat(x, 0), 0.0); - try { - Array.setFloat(new Object(), 0, (float) 9); - } catch (IllegalArgumentException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Passing non-array failed to throw exception"); - } - thrown = false; - try { - Array.setFloat(x, 4, (float) 9); - } catch (ArrayIndexOutOfBoundsException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Invalid index failed to throw exception"); - } - - thrown = false; - try { - Array.setFloat(null, 0, 0); - } catch (NullPointerException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Null argument failed to throw NPE"); - } - } - - /** - * java.lang.reflect.Array#setInt(java.lang.Object, int, int) - */ - public void test_setIntLjava_lang_ObjectII() { - // Test for method void java.lang.reflect.Array.setInt(java.lang.Object, - // int, int) - int[] x = { 0 }; - boolean thrown = false; - try { - Array.setInt(x, 0, (int) 1); - } catch (Exception e) { - fail("Exception during get test : " + e.getMessage()); - } - assertEquals("Get returned incorrect value", 1, Array.getInt(x, 0)); - try { - Array.setInt(new Object(), 0, (int) 9); - } catch (IllegalArgumentException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Passing non-array failed to throw exception"); - } - thrown = false; - try { - Array.setInt(x, 4, (int) 9); - } catch (ArrayIndexOutOfBoundsException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Invalid index failed to throw exception"); - } - - thrown = false; - try { - Array.setInt(null, 0, 0); - } catch (NullPointerException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Null argument failed to throw NPE"); - } - } - - /** - * java.lang.reflect.Array#setLong(java.lang.Object, int, long) - */ - public void test_setLongLjava_lang_ObjectIJ() { - // Test for method void - // java.lang.reflect.Array.setLong(java.lang.Object, int, long) - long[] x = { 0 }; - boolean thrown = false; - try { - Array.setLong(x, 0, 1); - } catch (Exception e) { - fail("Exception during get test : " + e.getMessage()); - } - assertEquals("Get returned incorrect value", 1, Array.getLong(x, 0)); - try { - Array.setLong(new Object(), 0, 9); - } catch (IllegalArgumentException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Passing non-array failed to throw exception"); - } - thrown = false; - try { - Array.setLong(x, 4, 9); - } catch (ArrayIndexOutOfBoundsException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Invalid index failed to throw exception"); - } - - thrown = false; - try { - Array.setLong(null, 0, 0); - } catch (NullPointerException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Null argument failed to throw NPE"); - } - } - - /** - * java.lang.reflect.Array#setShort(java.lang.Object, int, short) - */ - public void test_setShortLjava_lang_ObjectIS() { - // Test for method void - // java.lang.reflect.Array.setShort(java.lang.Object, int, short) - short[] x = { 0 }; - boolean thrown = false; - try { - Array.setShort(x, 0, (short) 1); - } catch (Exception e) { - fail("Exception during get test : " + e.getMessage()); - } - assertEquals("Get returned incorrect value", 1, Array.getShort(x, 0)); - try { - Array.setShort(new Object(), 0, (short) 9); - } catch (IllegalArgumentException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Passing non-array failed to throw exception"); - } - thrown = false; - try { - Array.setShort(x, 4, (short) 9); - } catch (ArrayIndexOutOfBoundsException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Invalid index failed to throw exception"); - } - - thrown = false; - try { - Array.setShort(null, 0, (short)0); - } catch (NullPointerException e) { - // Correct behaviour - thrown = true; - } - if (!thrown) { - fail("Null argument failed to throw NPE"); - } - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/lang/reflect/BoundedGenericMethodsTests.java b/luni/src/test/java/tests/api/java/lang/reflect/BoundedGenericMethodsTests.java deleted file mode 100644 index 7949a30..0000000 --- a/luni/src/test/java/tests/api/java/lang/reflect/BoundedGenericMethodsTests.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (C) 2008 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 tests.api.java.lang.reflect; - -import java.lang.reflect.Method; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; - -/** - * Tests bounded type parameters declared on methods. - */ -public class BoundedGenericMethodsTests extends GenericReflectionTestsBase { - @SuppressWarnings("unchecked") - static class BoundedGenericMethods<S> { - - public <T extends BoundedGenericMethods> void noParamNoReturn() {} - public <T extends BoundedGenericMethods> void paramNoReturn(T param) {} - - public <T extends BoundedGenericMethods> T noParamReturn() { - return (T) new Object(); - } - public <T extends BoundedGenericMethods> T paramReturn(T t) { - return t; - } - } - @SuppressWarnings("unchecked") - private static Class<? extends BoundedGenericMethods> clazz = BoundedGenericMethodsTests.BoundedGenericMethods.class; - - /** - * Tests whether the type parameter is upper bounded by BoundedGenericMethods. - * <T extends BoundedGenericMethods>. - * - * @param method - * the declaring method - */ - private void checkBoundedTypeParameter(Method method) { - TypeVariable<Method> typeParameter = getTypeParameter(method); - assertEquals("T", typeParameter.getName()); - assertEquals(method, typeParameter.getGenericDeclaration()); - - Type[] bounds = typeParameter.getBounds(); - assertLenghtOne(bounds); - Type bound = bounds[0]; - assertEquals(BoundedGenericMethods.class, bound); - } - - /** - * Tests whether the specified method declares a parameter with the type of - * the type parameter. - * - * @param method - * the declaring method - */ - private void parameterType(Method method) { - TypeVariable<Method> typeParameter = getTypeParameter(method); - assertLenghtOne(method.getGenericParameterTypes()); - Type genericParameterType = method.getGenericParameterTypes()[0]; - assertEquals(typeParameter, genericParameterType); - assertTrue(genericParameterType instanceof TypeVariable); - TypeVariable<?> typeVariable = (TypeVariable<?>) genericParameterType; - assertEquals(method, typeVariable.getGenericDeclaration()); - - Type[] paramBounds = typeVariable.getBounds(); - assertLenghtOne(paramBounds); - Type paramBound = paramBounds[0]; - assertEquals(BoundedGenericMethods.class, paramBound); - } - - @SuppressWarnings("unchecked") - private void checkReturnType(Method method) { - Type genericReturnType = method.getGenericReturnType(); - assertEquals(getTypeParameter(method), genericReturnType); - assertTrue(genericReturnType instanceof TypeVariable); - - TypeVariable<Method> returnTypeVariable = (TypeVariable<Method>) genericReturnType; - assertEquals(method, returnTypeVariable.getGenericDeclaration()); - - Type[] bounds = returnTypeVariable.getBounds(); - assertLenghtOne(bounds); - Type bound = bounds[0]; - - assertEquals(BoundedGenericMethods.class, bound); - } - - - - /** - * Tests that there are is one Type Parameter on the Class itself. - */ - public void testBoundedGenericMethods() { - assertLenghtOne(clazz.getTypeParameters()); - } - public void testNoParamNoReturn() throws SecurityException, NoSuchMethodException { - Method method = clazz.getMethod("noParamNoReturn"); - checkBoundedTypeParameter(method); - } - public void testUnboundedParamNoReturn() throws SecurityException, NoSuchMethodException { - Method method = clazz.getMethod("paramNoReturn", BoundedGenericMethods.class); - checkBoundedTypeParameter(method); - parameterType(method); - } - public void testNoParamReturn() throws SecurityException, NoSuchMethodException { - Method method = clazz.getMethod("noParamReturn"); - checkBoundedTypeParameter(method); - assertLenghtZero(method.getGenericParameterTypes()); - checkReturnType(method); - } - public void testUnboundedParamReturn() throws SecurityException, NoSuchMethodException { - Method method = clazz.getMethod("paramReturn", BoundedGenericMethods.class); - checkBoundedTypeParameter(method); - parameterType(method); - checkReturnType(method); - } -} diff --git a/luni/src/test/java/tests/api/java/lang/reflect/ConstructorTest.java b/luni/src/test/java/tests/api/java/lang/reflect/ConstructorTest.java deleted file mode 100644 index 932315c..0000000 --- a/luni/src/test/java/tests/api/java/lang/reflect/ConstructorTest.java +++ /dev/null @@ -1,443 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.lang.reflect; - -import java.lang.annotation.Annotation; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.lang.reflect.Constructor; -import java.lang.reflect.Modifier; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -public class ConstructorTest extends junit.framework.TestCase { - - - @Retention(RetentionPolicy.RUNTIME) - @Target( {ElementType.CONSTRUCTOR, ElementType.PARAMETER}) - static @interface ConstructorTestAnnotationRuntime0 { - } - - @Retention(RetentionPolicy.RUNTIME) - @Target( {ElementType.CONSTRUCTOR, ElementType.PARAMETER}) - static @interface ConstructorTestAnnotationRuntime1 { - } - - @Retention(RetentionPolicy.CLASS) - @Target( {ElementType.CONSTRUCTOR, ElementType.PARAMETER}) - static @interface ConstructorTestAnnotationClass0 { - } - - @Retention(RetentionPolicy.SOURCE) - @Target( {ElementType.CONSTRUCTOR, ElementType.PARAMETER}) - static @interface ConstructorTestAnnotationSource0 { - } - - static class ConstructorTestHelper extends Object { - int cval; - - @ConstructorTestAnnotationRuntime0 - @ConstructorTestAnnotationRuntime1 - @ConstructorTestAnnotationClass0 - @ConstructorTestAnnotationSource0 - public ConstructorTestHelper() throws IndexOutOfBoundsException { - cval = 99; - } - - public ConstructorTestHelper( - @ConstructorTestAnnotationRuntime0 - @ConstructorTestAnnotationRuntime1 - @ConstructorTestAnnotationClass0 - @ConstructorTestAnnotationSource0 Object x) { - } - - public ConstructorTestHelper(String... x) { - } - - private ConstructorTestHelper(int a) { - } - - protected ConstructorTestHelper(long a) { - } - - public int check() { - return cval; - } - } - - static class GenericConstructorTestHelper<T, S extends T, E extends Exception> { - public GenericConstructorTestHelper(T t, S s) {} - public GenericConstructorTestHelper() throws E{} - } - - static class NoPublicConstructorTestHelper { - // This class has no public constructor. - } - -// Used to test synthetic constructor. -// -// static class Outer { -// private Outer(){} -// class Inner { -// {new Outer();} -// } -// } - - public void test_getParameterAnnotations() throws Exception { - Constructor<ConstructorTestHelper> ctor1 = ConstructorTestHelper.class - .getConstructor(Object.class); - Annotation[][] paramAnnotations = ctor1.getParameterAnnotations(); - assertEquals("Annotations for wrong number of parameters returned", 1, - paramAnnotations.length); - assertEquals("Wrong number of annotations returned", 2, - paramAnnotations[0].length); - - Set<Class<?>> ignoreOrder = new HashSet<Class<?>>(); - ignoreOrder.add(paramAnnotations[0][0].annotationType()); - ignoreOrder.add(paramAnnotations[0][1].annotationType()); - - assertTrue("Missing ConstructorTestAnnotationRuntime0", ignoreOrder - .contains(ConstructorTestAnnotationRuntime0.class)); - assertTrue("Missing ConstructorTestAnnotationRuntime1", ignoreOrder - .contains(ConstructorTestAnnotationRuntime1.class)); - } - - - public void test_getDeclaredAnnotations() throws Exception { - Constructor<ConstructorTestHelper> ctor1 = null; - ctor1 = ConstructorTestHelper.class.getConstructor(new Class[0]); - Annotation[] annotations = ctor1.getDeclaredAnnotations(); - assertEquals("Wrong number of annotations returned", 2, - annotations.length); - Set<Class<?>> ignoreOrder = new HashSet<Class<?>>(); - ignoreOrder.add(annotations[0].annotationType()); - ignoreOrder.add(annotations[1].annotationType()); - - assertTrue("Missing ConstructorTestAnnotationRuntime0", ignoreOrder - .contains(ConstructorTestAnnotationRuntime0.class)); - assertTrue("Missing ConstructorTestAnnotationRuntime1", ignoreOrder - .contains(ConstructorTestAnnotationRuntime1.class)); - } - - public void test_isVarArgs() throws Exception { - Constructor<ConstructorTestHelper> varArgCtor = ConstructorTestHelper.class - .getConstructor(String[].class); - assertTrue("Vararg constructor not recognized", varArgCtor.isVarArgs()); - - Constructor<ConstructorTestHelper> nonVarArgCtor = ConstructorTestHelper.class - .getConstructor(Object.class); - assertFalse("Non vararg constructor recognized as vararg constructor", - nonVarArgCtor.isVarArgs()); - } - - public void test_hashCode() throws Exception { - Constructor<ConstructorTestHelper> constructor = ConstructorTestHelper.class - .getConstructor(); - assertEquals( - "The constructor's hashCode is not equal to the hashCode of the name of the declaring class", - ConstructorTestHelper.class.getName().hashCode(), constructor - .hashCode()); - } - - @SuppressWarnings("unchecked") - public void test_toGenericString() throws Exception { - Constructor<GenericConstructorTestHelper> genericCtor = GenericConstructorTestHelper.class - .getConstructor(Object.class, Object.class); - assertEquals( - "Wrong generic string returned", - "public tests.api.java.lang.reflect.ConstructorTest$GenericConstructorTestHelper(T,S)", - genericCtor.toGenericString()); - Constructor<GenericConstructorTestHelper> ctor = GenericConstructorTestHelper.class - .getConstructor(); - assertEquals( - "Wrong generic string returned", - "public tests.api.java.lang.reflect.ConstructorTest$GenericConstructorTestHelper() throws E", - ctor.toGenericString()); - } - - public void test_equalsLjava_lang_Object() { - Constructor<ConstructorTestHelper> ctor1 = null, ctor2 = null; - try { - ctor1 = ConstructorTestHelper.class.getConstructor( - new Class[0]); - ctor2 = ConstructorTestHelper.class.getConstructor(Object.class); - } catch (Exception e) { - fail("Exception during equals test : " + e.getMessage()); - } - assertTrue("Different Contructors returned equal", !ctor1.equals(ctor2)); - } - - public void test_getDeclaringClass() { - boolean val = false; - try { - Class<? extends ConstructorTestHelper> pclass = new ConstructorTestHelper().getClass(); - Constructor<? extends ConstructorTestHelper> ctor = pclass.getConstructor(new Class[0]); - val = ctor.getDeclaringClass().equals(pclass); - } catch (Exception e) { - fail("Exception during test : " + e.getMessage()); - } - assertTrue("Returned incorrect declaring class", val); - } - - public void test_getExceptionTypes() { - // Test for method java.lang.Class [] - // java.lang.reflect.Constructor.getExceptionTypes() - Class[] exceptions = null; - Class<? extends IndexOutOfBoundsException> ex = null; - try { - Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass() - .getConstructor(new Class[0]); - exceptions = ctor.getExceptionTypes(); - ex = new IndexOutOfBoundsException().getClass(); - } catch (Exception e) { - fail("Exception during test : " + e.getMessage()); - } - assertEquals("Returned exception list of incorrect length", - 1, exceptions.length); - assertTrue("Returned incorrect exception", exceptions[0].equals(ex)); - } - - public void test_getModifiers() { - // Test for method int java.lang.reflect.Constructor.getModifiers() - int mod = 0; - try { - Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass() - .getConstructor(new Class[0]); - mod = ctor.getModifiers(); - assertTrue("Returned incorrect modifers for public ctor", - ((mod & Modifier.PUBLIC) == Modifier.PUBLIC) - && ((mod & Modifier.PRIVATE) == 0)); - } catch (NoSuchMethodException e) { - fail("Exception during test : " + e.getMessage()); - } - try { - Class[] cl = { int.class }; - Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass() - .getDeclaredConstructor(cl); - mod = ctor.getModifiers(); - assertTrue("Returned incorrect modifers for private ctor", - ((mod & Modifier.PRIVATE) == Modifier.PRIVATE) - && ((mod & Modifier.PUBLIC) == 0)); - } catch (NoSuchMethodException e) { - fail("Exception during test : " + e.getMessage()); - } - try { - Class[] cl = { long.class }; - Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass() - .getDeclaredConstructor(cl); - mod = ctor.getModifiers(); - assertTrue("Returned incorrect modifers for private ctor", - ((mod & Modifier.PROTECTED) == Modifier.PROTECTED) - && ((mod & Modifier.PUBLIC) == 0)); - } catch (NoSuchMethodException e) { - fail("NoSuchMethodException during test : " + e.getMessage()); - } - } - - public void test_getName() { - // Test for method java.lang.String - // java.lang.reflect.Constructor.getName() - try { - Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass() - .getConstructor(new Class[0]); - assertTrue( - "Returned incorrect name: " + ctor.getName(), - ctor - .getName() - .equals( - "tests.api.java.lang.reflect.ConstructorTest$ConstructorTestHelper")); - } catch (Exception e) { - fail("Exception obtaining contructor : " + e.getMessage()); - } - } - - public void test_getParameterTypes() { - // Test for method java.lang.Class [] - // java.lang.reflect.Constructor.getParameterTypes() - Class[] types = null; - try { - Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass() - .getConstructor(new Class[0]); - types = ctor.getParameterTypes(); - } catch (Exception e) { - fail("Exception during getParameterTypes test:" - + e.toString()); - } - assertEquals("Incorrect parameter returned", 0, types.length); - - Class[] parms = null; - try { - parms = new Class[1]; - parms[0] = new Object().getClass(); - Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass() - .getConstructor(parms); - types = ctor.getParameterTypes(); - } catch (Exception e) { - fail("Exception during getParameterTypes test:" - + e.toString()); - } - assertTrue("Incorrect parameter returned", types[0].equals(parms[0])); - } - - @SuppressWarnings("unchecked") - public void test_getGenericParameterTypes() { - Type[] types = null; - try { - Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper() - .getClass().getConstructor(new Class[0]); - types = ctor.getGenericParameterTypes(); - } catch (Exception e) { - fail("Exception during getParameterTypes test:" + e.toString()); - } - assertEquals("Incorrect parameter returned", 0, types.length); - - Class<?>[] parms = null; - try { - parms = new Class[] {Object.class}; - Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper() - .getClass().getConstructor(parms); - types = ctor.getGenericParameterTypes(); - } catch (Exception e) { - fail("Exception during getParameterTypes test:" + e.toString()); - } - assertTrue("Incorrect parameter returned", types[0].equals(parms[0])); - - - try { - Constructor<GenericConstructorTestHelper> constructor = GenericConstructorTestHelper.class - .getConstructor(Object.class, Object.class); - types = constructor.getGenericParameterTypes(); - } catch (Exception e) { - fail("Exception during getParameterTypes test:" + e.toString()); - } - - assertEquals("Wrong number of parameter types returned", 2, - types.length); - - assertEquals("Wrong number of parameter types returned", "T", - ((TypeVariable)types[0]).getName()); - assertEquals("Wrong number of parameter types returned", "S", - ((TypeVariable)types[1]).getName()); - } - - @SuppressWarnings("unchecked") - public void test_getGenericExceptionTypes() { - Type[] types = null; - - try { - Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper() - .getClass().getConstructor(new Class[0]); - types = ctor.getGenericExceptionTypes(); - } catch (Exception e) { - fail("Exception during getGenericExceptionTypes test:" + e.toString()); - } - assertEquals("Wrong number of exception types returned", 1, types.length); - - - try { - Constructor<GenericConstructorTestHelper> constructor = GenericConstructorTestHelper.class - .getConstructor(); - types = constructor.getGenericExceptionTypes(); - } catch (Exception e) { - fail("Exception during getGenericExceptionTypes test:" - + e.toString()); - } - - assertEquals("Wrong number of exception types returned", 1, - types.length); - - assertEquals("Wrong exception name returned.", "E", - ((TypeVariable)types[0]).getName()); - - } - - - public void test_newInstance$Ljava_lang_Object() { - // Test for method java.lang.Object - // java.lang.reflect.Constructor.newInstance(java.lang.Object []) - - ConstructorTestHelper test = null; - try { - Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass() - .getConstructor(new Class[0]); - test = ctor.newInstance((Object[])null); - } catch (Exception e) { - fail("Failed to create instance : " + e.getMessage()); - } - assertEquals("improper instance created", 99, test.check()); - } - - public void test_toString() { - // Test for method java.lang.String - // java.lang.reflect.Constructor.toString() - Class[] parms = null; - Constructor<? extends ConstructorTestHelper> ctor = null; - try { - parms = new Class[1]; - parms[0] = new Object().getClass(); - ctor = new ConstructorTestHelper().getClass().getConstructor(parms); - } catch (Exception e) { - fail("Exception during getParameterTypes test:" - + e.toString()); - } - assertTrue( - "Returned incorrect string representation: " + ctor.toString(), - ctor - .toString() - .equals( - "public tests.api.java.lang.reflect.ConstructorTest$ConstructorTestHelper(java.lang.Object)")); - } - - public void test_getConstructor() throws Exception { - // Passing new Class[0] should be equivalent to (Class[]) null. - Class<ConstructorTestHelper> c2 = ConstructorTestHelper.class; - assertEquals(c2.getConstructor(new Class[0]), c2.getConstructor((Class[]) null)); - assertEquals(c2.getDeclaredConstructor(new Class[0]), - c2.getDeclaredConstructor((Class[]) null)); - - // We can get a non-public constructor via getDeclaredConstructor... - Class<NoPublicConstructorTestHelper> c1 = NoPublicConstructorTestHelper.class; - c1.getDeclaredConstructor((Class[]) null); - // ...but not with getConstructor (which only returns public constructors). - try { - c1.getConstructor((Class[]) null); - fail("Should throw NoSuchMethodException"); - } catch (NoSuchMethodException ex) { - // Expected. - } - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/lang/reflect/FieldTest.java b/luni/src/test/java/tests/api/java/lang/reflect/FieldTest.java deleted file mode 100644 index a1ca151..0000000 --- a/luni/src/test/java/tests/api/java/lang/reflect/FieldTest.java +++ /dev/null @@ -1,1868 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.lang.reflect; - -import tests.support.Support_Field; - -import java.lang.annotation.Annotation; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.util.HashSet; -import java.util.Set; - -public class FieldTest extends junit.framework.TestCase { - - // BEGIN android-note - // This test had a couple of bugs in it. Some parts of the code were - // unreachable before. Also some tests expected the wrong excpetions - // to be thrown. This version has been validated to pass on a standard - // JDK 1.5. - // END android-note - - public class TestClass { - @AnnotationRuntime0 - @AnnotationRuntime1 - @AnnotationClass0 - @AnnotationSource0 - public int annotatedField; - class Inner{} - } - - - @Retention(RetentionPolicy.RUNTIME) - @Target( {ElementType.FIELD}) - static @interface AnnotationRuntime0 { - } - - @Retention(RetentionPolicy.RUNTIME) - @Target( { ElementType.FIELD}) - static @interface AnnotationRuntime1 { - } - - @Retention(RetentionPolicy.CLASS) - @Target( { ElementType.FIELD}) - static @interface AnnotationClass0 { - } - - @Retention(RetentionPolicy.SOURCE) - @Target( {ElementType.FIELD}) - static @interface AnnotationSource0 { - } - - @Inherited - @Retention(RetentionPolicy.RUNTIME) - @Target( {ElementType.FIELD}) - static @interface InheritedRuntime { - } - - public class GenericField<S, T extends Number> { - S field; - T boundedField; - int intField; - } - - - static class TestField { - public static int pubfield1; - - private static int privfield1 = 123; - - protected int intField = Integer.MAX_VALUE; - protected final int intFField = Integer.MAX_VALUE; - protected static int intSField = Integer.MAX_VALUE; - private final int intPFField = Integer.MAX_VALUE; - - protected short shortField = Short.MAX_VALUE; - protected final short shortFField = Short.MAX_VALUE; - protected static short shortSField = Short.MAX_VALUE; - private final short shortPFField = Short.MAX_VALUE; - - protected boolean booleanField = true; - protected static boolean booleanSField = true; - protected final boolean booleanFField = true; - private final boolean booleanPFField = true; - - protected byte byteField = Byte.MAX_VALUE; - protected static byte byteSField = Byte.MAX_VALUE; - protected final byte byteFField = Byte.MAX_VALUE; - private final byte bytePFField = Byte.MAX_VALUE; - - protected long longField = Long.MAX_VALUE; - protected final long longFField = Long.MAX_VALUE; - protected static long longSField = Long.MAX_VALUE; - private final long longPFField = Long.MAX_VALUE; - - protected double doubleField = Double.MAX_VALUE; - protected static double doubleSField = Double.MAX_VALUE; - protected static final double doubleSFField = Double.MAX_VALUE; - protected final double doubleFField = Double.MAX_VALUE; - private final double doublePFField = Double.MAX_VALUE; - - protected float floatField = Float.MAX_VALUE; - protected final float floatFField = Float.MAX_VALUE; - protected static float floatSField = Float.MAX_VALUE; - private final float floatPFField = Float.MAX_VALUE; - - protected char charField = 'T'; - protected static char charSField = 'T'; - private final char charPFField = 'T'; - - protected final char charFField = 'T'; - - private static final int x = 1; - - public volatile transient int y = 0; - - protected static transient volatile int prsttrvol = 99; - } - - public class TestFieldSub1 extends TestField { - } - - public class TestFieldSub2 extends TestField { - } - - static class A { - protected short shortField = Short.MAX_VALUE; - } - - static enum TestEnum { - A, B, C; - int field; - } - - /** - * java.lang.reflect.Field#equals(java.lang.Object) - */ - public void test_equalsLjava_lang_Object() { - // Test for method boolean - // java.lang.reflect.Field.equals(java.lang.Object) - TestField x = new TestField(); - Field f = null; - try { - f = x.getClass().getDeclaredField("shortField"); - } catch (Exception e) { - fail("Exception during getType test : " + e.getMessage()); - } - try { - assertTrue("Same Field returned false", f.equals(f)); - assertTrue("Inherited Field returned false", f.equals(x.getClass() - .getDeclaredField("shortField"))); - assertTrue("Identical Field from different class returned true", !f - .equals(A.class.getDeclaredField("shortField"))); - } catch (Exception e) { - fail("Exception during getType test : " + e.getMessage()); - } - } - - /** - * java.lang.reflect.Field#get(java.lang.Object) - */ - public void test_getLjava_lang_Object() throws Throwable { - // Test for method java.lang.Object - // java.lang.reflect.Field.get(java.lang.Object) - TestField x = new TestField(); - Field f = x.getClass().getDeclaredField("doubleField"); - Double val = (Double) f.get(x); - - assertTrue("Returned incorrect double field value", - val.doubleValue() == Double.MAX_VALUE); - // Test getting a static field; - f = x.getClass().getDeclaredField("doubleSField"); - f.set(x, new Double(1.0)); - val = (Double) f.get(x); - assertEquals("Returned incorrect double field value", 1.0, val - .doubleValue()); - - // Try a get on a private field - boolean thrown = false; - try { - f = TestAccess.class.getDeclaredField("xxx"); - assertNotNull(f); - f.get(null); - fail("No expected IllegalAccessException"); - } catch (IllegalAccessException ok) { - thrown = true; - } - assertTrue("IllegalAccessException expected but not thrown", thrown); - - // Try a get on a private field in nested member - // temporarily commented because it breaks J9 VM - // Regression for HARMONY-1309 - //f = x.getClass().getDeclaredField("privfield1"); - //assertEquals(x.privfield1, f.get(x)); - - // Try a get using an invalid class. - thrown = false; - try { - f = x.getClass().getDeclaredField("doubleField"); - f.get(new String()); - fail("No expected IllegalArgumentException"); - } catch (IllegalArgumentException exc) { - // Correct - Passed an Object that does not declare or inherit f - thrown = true; - } - assertTrue("IllegalArgumentException expected but not thrown", thrown); - - //Test NPE - thrown = false; - try { - f = TestField.class.getDeclaredField("intField"); - f.get(null); - fail("Expected NullPointerException not thrown"); - } catch (NullPointerException exc) { - // Correct - Passed an Object that does not declare or inherit f - thrown = true; - } - assertTrue("NullPointerException expected but not thrown", thrown); - - //Test no NPE on static fields - thrown = false; - try { - f = TestField.class.getDeclaredField("doubleSField"); - f.get(null); - assertTrue("Exception thrown", true); - } catch (Exception exc) { - fail("No exception expected"); - } - } - - class SupportSubClass extends Support_Field { - - Object getField(char primitiveType, Object o, Field f, - Class expectedException) { - Object res = null; - try { - primitiveType = Character.toUpperCase(primitiveType); - switch (primitiveType) { - case 'I': // int - res = new Integer(f.getInt(o)); - break; - case 'J': // long - res = new Long(f.getLong(o)); - break; - case 'Z': // boolean - res = new Boolean(f.getBoolean(o)); - break; - case 'S': // short - res = new Short(f.getShort(o)); - break; - case 'B': // byte - res = new Byte(f.getByte(o)); - break; - case 'C': // char - res = new Character(f.getChar(o)); - break; - case 'D': // double - res = new Double(f.getDouble(o)); - break; - case 'F': // float - res = new Float(f.getFloat(o)); - break; - default: - res = f.get(o); - } - if (expectedException != null) { - fail("expected exception " + expectedException.getName()); - } - } catch (Exception e) { - if (expectedException == null) { - fail("unexpected exception " + e); - } else { - assertTrue("expected exception " - + expectedException.getName() + " and got " + e, e - .getClass().equals(expectedException)); - } - } - return res; - } - - void setField(char primitiveType, Object o, Field f, - Class expectedException, Object value) { - try { - primitiveType = Character.toUpperCase(primitiveType); - switch (primitiveType) { - case 'I': // int - f.setInt(o, ((Integer) value).intValue()); - break; - case 'J': // long - f.setLong(o, ((Long) value).longValue()); - break; - case 'Z': // boolean - f.setBoolean(o, ((Boolean) value).booleanValue()); - break; - case 'S': // short - f.setShort(o, ((Short) value).shortValue()); - break; - case 'B': // byte - f.setByte(o, ((Byte) value).byteValue()); - break; - case 'C': // char - f.setChar(o, ((Character) value).charValue()); - break; - case 'D': // double - f.setDouble(o, ((Double) value).doubleValue()); - break; - case 'F': // float - f.setFloat(o, ((Float) value).floatValue()); - break; - default: - f.set(o, value); - } - if (expectedException != null) { - fail("expected exception " + expectedException.getName() - + " for field " + f.getName() + ", value " + value); - } - } catch (Exception e) { - if (expectedException == null) { - fail("unexpected exception " + e + " for field " - + f.getName() + ", value " + value); - } else { - assertTrue("expected exception " - + expectedException.getName() + " and got " + e - + " for field " + f.getName() + ", value " + value, - e.getClass().equals(expectedException)); - } - } - } - } - - /** - * java.lang.reflect.Field#get(java.lang.Object) - * java.lang.reflect.Field#getByte(java.lang.Object) - * java.lang.reflect.Field#getBoolean(java.lang.Object) - * java.lang.reflect.Field#getShort(java.lang.Object) - * java.lang.reflect.Field#getInt(java.lang.Object) - * java.lang.reflect.Field#getLong(java.lang.Object) - * java.lang.reflect.Field#getFloat(java.lang.Object) - * java.lang.reflect.Field#getDouble(java.lang.Object) - * java.lang.reflect.Field#getChar(java.lang.Object) - * java.lang.reflect.Field#set(java.lang.Object, java.lang.Object) - * java.lang.reflect.Field#setByte(java.lang.Object, byte) - * java.lang.reflect.Field#setBoolean(java.lang.Object, boolean) - * java.lang.reflect.Field#setShort(java.lang.Object, short) - * java.lang.reflect.Field#setInt(java.lang.Object, int) - * java.lang.reflect.Field#setLong(java.lang.Object, long) - * java.lang.reflect.Field#setFloat(java.lang.Object, float) - * java.lang.reflect.Field#setDouble(java.lang.Object, double) - * java.lang.reflect.Field#setChar(java.lang.Object, char) - */ - public void testProtectedFieldAccess() { - Class fieldClass = new Support_Field().getClass(); - String fieldName = null; - Field objectField = null; - Field booleanField = null; - Field byteField = null; - Field charField = null; - Field shortField = null; - Field intField = null; - Field longField = null; - Field floatField = null; - Field doubleField = null; - try { - fieldName = "objectField"; - objectField = fieldClass.getDeclaredField(fieldName); - - fieldName = "booleanField"; - booleanField = fieldClass.getDeclaredField(fieldName); - - fieldName = "byteField"; - byteField = fieldClass.getDeclaredField(fieldName); - - fieldName = "charField"; - charField = fieldClass.getDeclaredField(fieldName); - - fieldName = "shortField"; - shortField = fieldClass.getDeclaredField(fieldName); - - fieldName = "intField"; - intField = fieldClass.getDeclaredField(fieldName); - - fieldName = "longField"; - longField = fieldClass.getDeclaredField(fieldName); - - fieldName = "floatField"; - floatField = fieldClass.getDeclaredField(fieldName); - - fieldName = "doubleField"; - doubleField = fieldClass.getDeclaredField(fieldName); - } catch (NoSuchFieldException e) { - fail("missing field " + fieldName + " in test support class " - + fieldClass.getName()); - } - - // create the various objects that might or might not have an instance - // of the field - Support_Field parentClass = new Support_Field(); - SupportSubClass subclass = new SupportSubClass(); - SupportSubClass otherSubclass = new SupportSubClass(); - Object plainObject = new Object(); - - Class illegalAccessExceptionClass = new IllegalAccessException() - .getClass(); - Class illegalArgumentExceptionClass = new IllegalArgumentException() - .getClass(); - - // The test will attempt to use pass an object to set for object, byte, - // short, ..., float and double fields - // and pass a byte to to setByte for byte, short, ..., float and double - // fields and so on. - // It will also test if IllegalArgumentException is thrown when the - // field does not exist in the given object and that - // IllegalAccessException is thrown when trying to access an - // inaccessible protected field. - // The test will also check that IllegalArgumentException is thrown for - // all other attempts. - - // Ordered by widening conversion, except for 'L' at the beg (which - // stands for Object). - // If the object provided to set can be unwrapped to a primitive, then - // the set method can set - // primitive fields. - char types[] = { 'L', 'B', 'S', 'C', 'I', 'J', 'F', 'D' }; - Field fields[] = { objectField, byteField, shortField, charField, - intField, longField, floatField, doubleField }; - Object values[] = { new Byte((byte) 1), new Byte((byte) 1), - new Short((short) 1), new Character((char) 1), new Integer(1), - new Long(1), new Float(1), new Double(1) }; - - // test set methods - for (int i = 0; i < types.length; i++) { - char type = types[i]; - Object value = values[i]; - for (int j = i; j < fields.length; j++) { - Field field = fields[j]; - fieldName = field.getName(); - - if (field == charField && type != 'C') { - // the exception is that bytes and shorts CANNOT be - // converted into chars even though chars CAN be - // converted into ints, longs, floats and doubles - subclass.setField(type, subclass, field, - illegalArgumentExceptionClass, value); - } else { - // setting type into field); - subclass.setField(type, subclass, field, null, value); - subclass.setField(type, otherSubclass, field, null, value); - subclass.setField(type, parentClass, field, - illegalAccessExceptionClass, value); - subclass.setField(type, plainObject, field, - // Failed on JDK. - illegalAccessExceptionClass, value); - } - } - for (int j = 0; j < i; j++) { - Field field = fields[j]; - fieldName = field.getName(); - // not setting type into field); - subclass.setField(type, subclass, field, - illegalArgumentExceptionClass, value); - } - } - - // test setBoolean - Boolean booleanValue = Boolean.TRUE; - subclass.setField('Z', subclass, booleanField, null, booleanValue); - subclass.setField('Z', otherSubclass, booleanField, null, booleanValue); - subclass.setField('Z', parentClass, booleanField, - illegalAccessExceptionClass, booleanValue); - subclass.setField('Z', plainObject, booleanField, - // Failed on JDK - illegalAccessExceptionClass, booleanValue); - for (int j = 0; j < fields.length; j++) { - Field listedField = fields[j]; - fieldName = listedField.getName(); - // not setting boolean into listedField - subclass.setField('Z', subclass, listedField, - illegalArgumentExceptionClass, booleanValue); - } - for (int i = 0; i < types.length; i++) { - char type = types[i]; - Object value = values[i]; - subclass.setField(type, subclass, booleanField, - illegalArgumentExceptionClass, value); - } - - // We perform the analagous test on the get methods. - - // ordered by widening conversion, except for 'L' at the end (which - // stands for Object), to which all primitives can be converted by - // wrapping - char newTypes[] = new char[] { 'B', 'S', 'C', 'I', 'J', 'F', 'D', 'L' }; - Field newFields[] = { byteField, shortField, charField, intField, - longField, floatField, doubleField, objectField }; - fields = newFields; - types = newTypes; - // test get methods - for (int i = 0; i < types.length; i++) { - char type = types[i]; - for (int j = 0; j <= i; j++) { - Field field = fields[j]; - fieldName = field.getName(); - if (type == 'C' && field != charField) { - // the exception is that bytes and shorts CANNOT be - // converted into chars even though chars CAN be - // converted into ints, longs, floats and doubles - subclass.getField(type, subclass, field, - illegalArgumentExceptionClass); - } else { - // getting type from field - subclass.getField(type, subclass, field, null); - subclass.getField(type, otherSubclass, field, null); - subclass.getField(type, parentClass, field, - illegalAccessExceptionClass); - subclass.getField(type, plainObject, field, - illegalAccessExceptionClass); - } - } - for (int j = i + 1; j < fields.length; j++) { - Field field = fields[j]; - fieldName = field.getName(); - subclass.getField(type, subclass, field, - illegalArgumentExceptionClass); - } - } - - // test getBoolean - subclass.getField('Z', subclass, booleanField, null); - subclass.getField('Z', otherSubclass, booleanField, null); - subclass.getField('Z', parentClass, booleanField, - illegalAccessExceptionClass); - subclass.getField('Z', plainObject, booleanField, - illegalAccessExceptionClass); - for (int j = 0; j < fields.length; j++) { - Field listedField = fields[j]; - fieldName = listedField.getName(); - // not getting boolean from listedField - subclass.getField('Z', subclass, listedField, - illegalArgumentExceptionClass); - } - for (int i = 0; i < types.length - 1; i++) { - char type = types[i]; - subclass.getField(type, subclass, booleanField, - illegalArgumentExceptionClass); - } - Object res = subclass.getField('L', subclass, booleanField, null); - assertTrue("unexpected object " + res, res instanceof Boolean); - } - - /** - * java.lang.reflect.Field#getBoolean(java.lang.Object) - */ - public void test_getBooleanLjava_lang_Object() { - TestField x = new TestField(); - Field f = null; - boolean val = false; - try { - f = x.getClass().getDeclaredField("booleanField"); - val = f.getBoolean(x); - } catch (Exception e) { - fail("Exception during getBoolean test: " + e.toString()); - } - assertTrue("Returned incorrect boolean field value", val); - - boolean thrown = false; - try { - f = x.getClass().getDeclaredField("doubleField"); - f.getBoolean(x); - fail("IllegalArgumentException expected but not thrown"); - } catch (IllegalArgumentException ex) { - thrown = true; - } catch (Exception ex) { - fail("IllegalArgumentException expected but not thrown"); - } - assertTrue("IllegalArgumentException expected but not thrown", thrown); - - thrown = false; - try { - f = x.getClass().getDeclaredField("booleanPFField"); - f.getBoolean(x); - fail("IllegalAccessException expected but not thrown"); - } catch (IllegalAccessException ex) { - thrown = true; - } catch (Exception ex) { - fail("IllegalAccessException expected but not thrown" - + ex.getMessage()); - } - assertTrue("IllegalAccessException expected but not thrown", thrown); - - //Test NPE - thrown = false; - try { - f = x.getClass().getDeclaredField("booleanField"); - f.getBoolean(null); - fail("NullPointerException expected but not thrown"); - } catch (NullPointerException ex) { - thrown = true; - } catch (Exception ex) { - fail("NullPointerException expected but not thrown"); - } - assertTrue("NullPointerException expected but not thrown", thrown); - - //Test no NPE on static field - thrown = false; - try { - f = x.getClass().getDeclaredField("booleanSField"); - boolean staticValue = f.getBoolean(null); - assertTrue("Wrong value returned", staticValue); - } catch (Exception ex) { - fail("No exception expected"); - } - } - - - /** - * java.lang.reflect.Field#getByte(java.lang.Object) - */ - public void test_getByteLjava_lang_Object() { - // Test for method byte - // java.lang.reflect.Field.getByte(java.lang.Object) - TestField x = new TestField(); - Field f = null; - byte val = 0; - try { - f = x.getClass().getDeclaredField("byteField"); - val = f.getByte(x); - } catch (Exception e) { - fail("Exception during getbyte test : " + e.getMessage()); - } - assertTrue("Returned incorrect byte field value", val == Byte.MAX_VALUE); - - boolean thrown = false; - try { - f = x.getClass().getDeclaredField("doubleField"); - f.getByte(x); - fail("IllegalArgumentException expected but not thrown"); - } catch (IllegalArgumentException ex) { - thrown = true; - } catch (Exception ex) { - fail("IllegalArgumentException expected but not thrown"); - } - assertTrue("IllegalArgumentException expected but not thrown", thrown); - - thrown = false; - try { - f = x.getClass().getDeclaredField("bytePFField"); - f.getByte(x); - fail("IllegalAccessException expected but not thrown"); - } catch (IllegalAccessException ex) { - thrown = true; - } catch (Exception ex) { - fail("IllegalAccessException expected but not thrown" - + ex.getMessage()); - } - assertTrue("IllegalAccessException expected but not thrown", thrown); - - //Test NPE - thrown = false; - try { - f = x.getClass().getDeclaredField("byteField"); - f.getByte(null); - fail("NullPointerException expected but not thrown"); - } catch (NullPointerException ex) { - thrown = true; - } catch (Exception ex) { - fail("NullPointerException expected but not thrown"); - } - assertTrue("NullPointerException expected but not thrown", thrown); - - //Test no NPE on static field - thrown = false; - try { - f = x.getClass().getDeclaredField("byteSField"); - byte staticValue = f.getByte(null); - assertEquals("Wrong value returned", Byte.MAX_VALUE, staticValue); - } catch (Exception ex) { - fail("No exception expected "+ ex.getMessage()); - } - } - - /** - * java.lang.reflect.Field#getChar(java.lang.Object) - */ - public void test_getCharLjava_lang_Object() { - // Test for method char - // java.lang.reflect.Field.getChar(java.lang.Object) - TestField x = new TestField(); - Field f = null; - char val = 0; - try { - f = x.getClass().getDeclaredField("charField"); - val = f.getChar(x); - } catch (Exception e) { - fail("Exception during getCharacter test: " + e.toString()); - } - assertEquals("Returned incorrect char field value", 'T', val); - - boolean thrown = false; - try { - f = x.getClass().getDeclaredField("doubleField"); - f.getChar(x); - fail("IllegalArgumentException expected but not thrown"); - } catch (IllegalArgumentException ex) { - thrown = true; - } catch (Exception ex) { - fail("IllegalArgumentException expected but not thrown"); - } - assertTrue("IllegalArgumentException expected but not thrown", thrown); - - thrown = false; - try { - f = x.getClass().getDeclaredField("charPFField"); - f.getChar(x); - fail("IllegalAccessException expected but not thrown"); - } catch (IllegalAccessException ex) { - thrown = true; - } catch (Exception ex) { - fail("IllegalAccessException expected but not thrown" - + ex.getMessage()); - } - assertTrue("IllegalAccessException expected but not thrown", thrown); - - //Test NPE - thrown = false; - try { - f = x.getClass().getDeclaredField("charField"); - f.getChar(null); - fail("NullPointerException expected but not thrown"); - } catch (NullPointerException ex) { - thrown = true; - } catch (Exception ex) { - fail("NullPointerException expected but not thrown"); - } - assertTrue("NullPointerException expected but not thrown", thrown); - - //Test no NPE on static field - thrown = false; - try { - f = x.getClass().getDeclaredField("charSField"); - char staticValue = f.getChar(null); - assertEquals("Wrong value returned", 'T', staticValue); - } catch (Exception ex) { - fail("No exception expected "+ ex.getMessage()); - } - } - - /** - * java.lang.reflect.Field#getDeclaringClass() - */ - public void test_getDeclaringClass() { - // Test for method java.lang.Class - // java.lang.reflect.Field.getDeclaringClass() - Field[] fields; - - try { - fields = new TestField().getClass().getFields(); - assertTrue("Returned incorrect declaring class", fields[0] - .getDeclaringClass().equals(new TestField().getClass())); - - // Check the case where the field is inherited to be sure the parent - // is returned as the declarator - fields = new TestFieldSub1().getClass().getFields(); - assertTrue("Returned incorrect declaring class", fields[0] - .getDeclaringClass().equals(new TestField().getClass())); - } catch (Exception e) { - fail("Exception : " + e.getMessage()); - } - } - - /** - * java.lang.reflect.Field#getDouble(java.lang.Object) - */ - public void test_getDoubleLjava_lang_Object() { - // Test for method double - // java.lang.reflect.Field.getDouble(java.lang.Object) - TestField x = new TestField(); - Field f = null; - double val = 0.0; - try { - f = x.getClass().getDeclaredField("doubleField"); - val = f.getDouble(x); - } catch (Exception e) { - fail("Exception during getDouble test: " + e.toString()); - } - assertTrue("Returned incorrect double field value", - val == Double.MAX_VALUE); - - boolean thrown = false; - try { - f = x.getClass().getDeclaredField("booleanField"); - f.getDouble(x); - fail("IllegalArgumentException expected but not thrown"); - } catch (IllegalArgumentException ex) { - thrown = true; - } catch (Exception ex) { - fail("IllegalArgumentException expected but not thrown " - + ex.getMessage()); - } - assertTrue("IllegalArgumentException expected but not thrown", thrown); - - thrown = false; - try { - f = x.getClass().getDeclaredField("doublePFField"); - f.getDouble(x); - fail("IllegalAccessException expected but not thrown"); - } catch (IllegalAccessException ex) { - thrown = true; - } catch (Exception ex) { - fail("IllegalAccessException expected but not thrown" - + ex.getMessage()); - } - assertTrue("IllegalAccessException expected but not thrown", thrown); - - //Test NPE - thrown = false; - try { - f = x.getClass().getDeclaredField("doubleField"); - f.getDouble(null); - fail("NullPointerException expected but not thrown"); - } catch (NullPointerException ex) { - thrown = true; - } catch (Exception ex) { - fail("NullPointerException expected but not thrown"); - } - assertTrue("NullPointerException expected but not thrown", thrown); - - //Test no NPE on static field - thrown = false; - try { - f = x.getClass().getDeclaredField("doubleSFField"); - double staticValue = f.getDouble(null); - assertEquals("Wrong value returned", Double.MAX_VALUE, staticValue); - } catch (Exception ex) { - fail("No exception expected "+ ex.getMessage()); - } - } - - /** - * java.lang.reflect.Field#getFloat(java.lang.Object) - */ - public void test_getFloatLjava_lang_Object() { - // Test for method float - // java.lang.reflect.Field.getFloat(java.lang.Object) - TestField x = new TestField(); - Field f = null; - float val = 0; - try { - f = x.getClass().getDeclaredField("floatField"); - val = f.getFloat(x); - } catch (Exception e) { - fail("Exception during getFloat test : " + e.getMessage()); - } - assertTrue("Returned incorrect float field value", - val == Float.MAX_VALUE); - - boolean thrown = false; - try { - f = x.getClass().getDeclaredField("booleanField"); - f.getFloat(x); - fail("IllegalArgumentException expected but not thrown"); - } catch (IllegalArgumentException ex) { - thrown = true; - } catch (Exception ex) { - fail("IllegalArgumentException expected but not thrown " - + ex.getMessage()); - } - assertTrue("IllegalArgumentException expected but not thrown", thrown); - - thrown = false; - try { - f = x.getClass().getDeclaredField("floatPFField"); - f.getFloat(x); - fail("IllegalAccessException expected but not thrown"); - } catch (IllegalAccessException ex) { - thrown = true; - } catch (Exception ex) { - fail("IllegalAccessException expected but not thrown" - + ex.getMessage()); - } - assertTrue("IllegalAccessException expected but not thrown", thrown); - - //Test NPE - thrown = false; - try { - f = x.getClass().getDeclaredField("floatField"); - f.getFloat(null); - fail("NullPointerException expected but not thrown"); - } catch (NullPointerException ex) { - thrown = true; - } catch (Exception ex) { - fail("NullPointerException expected but not thrown"); - } - assertTrue("NullPointerException expected but not thrown", thrown); - - //Test no NPE on static field - thrown = false; - try { - f = x.getClass().getDeclaredField("floatSField"); - float staticValue = f.getFloat(null); - assertEquals("Wrong value returned", Float.MAX_VALUE, staticValue); - } catch (Exception ex) { - fail("No exception expected "+ ex.getMessage()); - } - } - - /** - * java.lang.reflect.Field#getInt(java.lang.Object) - */ - public void test_getIntLjava_lang_Object() { - // Test for method int java.lang.reflect.Field.getInt(java.lang.Object) - TestField x = new TestField(); - Field f = null; - int val = 0; - try { - f = x.getClass().getDeclaredField("intField"); - val = f.getInt(x); - } catch (Exception e) { - fail("Exception during getInt test : " + e.getMessage()); - } - assertTrue("Returned incorrect Int field value", - val == Integer.MAX_VALUE); - - boolean thrown = false; - try { - f = x.getClass().getDeclaredField("booleanField"); - f.getInt(x); - fail("IllegalArgumentException expected but not thrown"); - } catch (IllegalArgumentException ex) { - thrown = true; - } catch (Exception ex) { - fail("IllegalArgumentException expected but not thrown " - + ex.getMessage()); - } - assertTrue("IllegalArgumentException expected but not thrown", thrown); - - thrown = false; - try { - f = x.getClass().getDeclaredField("intPFField"); - f.getInt(x); - fail("IllegalAccessException expected but not thrown"); - } catch (IllegalAccessException ex) { - thrown = true; - } catch (Exception ex) { - fail("IllegalAccessException expected but not thrown" - + ex.getMessage()); - } - assertTrue("IllegalAccessException expected but not thrown", thrown); - - //Test NPE - thrown = false; - try { - f = x.getClass().getDeclaredField("intField"); - f.getInt(null); - fail("NullPointerException expected but not thrown"); - } catch (NullPointerException ex) { - thrown = true; - } catch (Exception ex) { - fail("NullPointerException expected but not thrown"); - } - assertTrue("NullPointerException expected but not thrown", thrown); - - //Test no NPE on static field - thrown = false; - try { - f = x.getClass().getDeclaredField("intSField"); - int staticValue = f.getInt(null); - assertEquals("Wrong value returned", Integer.MAX_VALUE, staticValue); - } catch (Exception ex) { - fail("No exception expected " + ex.getMessage()); - } - - } - - /** - * java.lang.reflect.Field#getLong(java.lang.Object) - */ - public void test_getLongLjava_lang_Object() { - // Test for method long - // java.lang.reflect.Field.getLong(java.lang.Object) - TestField x = new TestField(); - Field f = null; - long val = 0; - try { - f = x.getClass().getDeclaredField("longField"); - val = f.getLong(x); - } catch (Exception e) { - fail("Exception during getLong test : " + e.getMessage()); - } - - boolean thrown = false; - try { - f = x.getClass().getDeclaredField("booleanField"); - f.getLong(x); - fail("IllegalArgumentException expected but not thrown"); - } catch (IllegalArgumentException ex) { - thrown = true; - } catch (Exception ex) { - fail("IllegalArgumentException expected but not thrown " - + ex.getMessage()); - } - assertTrue("IllegalArgumentException expected but not thrown", thrown); - - thrown = false; - try { - f = x.getClass().getDeclaredField("longPFField"); - f.getLong(x); - fail("IllegalAccessException expected but not thrown"); - } catch (IllegalAccessException ex) { - thrown = true; - } catch (Exception ex) { - fail("IllegalAccessException expected but not thrown" - + ex.getMessage()); - } - assertTrue("IllegalAccessException expected but not thrown", thrown); - - //Test NPE - thrown = false; - try { - f = x.getClass().getDeclaredField("longField"); - f.getLong(null); - fail("NullPointerException expected but not thrown"); - } catch (NullPointerException ex) { - thrown = true; - } catch (Exception ex) { - fail("NullPointerException expected but not thrown"); - } - assertTrue("NullPointerException expected but not thrown", thrown); - - //Test no NPE on static field - thrown = false; - try { - f = x.getClass().getDeclaredField("longSField"); - long staticValue = f.getLong(null); - assertEquals("Wrong value returned", Long.MAX_VALUE, staticValue); - } catch (Exception ex) { - fail("No exception expected "+ ex.getMessage()); - } - } - - /** - * java.lang.reflect.Field#getModifiers() - */ - public void test_getModifiers() { - // Test for method int java.lang.reflect.Field.getModifiers() - TestField x = new TestField(); - Field f = null; - try { - f = x.getClass().getDeclaredField("prsttrvol"); - } catch (Exception e) { - fail("Exception during getModifiers test: " + e.toString()); - } - int mod = f.getModifiers(); - int mask = (Modifier.PROTECTED | Modifier.STATIC) - | (Modifier.TRANSIENT | Modifier.VOLATILE); - int nmask = (Modifier.PUBLIC | Modifier.NATIVE); - assertTrue("Returned incorrect field modifiers: ", - ((mod & mask) == mask) && ((mod & nmask) == 0)); - } - - /** - * java.lang.reflect.Field#getName() - */ - public void test_getName() { - // Test for method java.lang.String java.lang.reflect.Field.getName() - TestField x = new TestField(); - Field f = null; - try { - f = x.getClass().getDeclaredField("shortField"); - } catch (Exception e) { - fail("Exception during getType test : " + e.getMessage()); - } - assertEquals("Returned incorrect field name", - "shortField", f.getName()); - } - - /** - * java.lang.reflect.Field#getShort(java.lang.Object) - */ - public void test_getShortLjava_lang_Object() { - // Test for method short - // java.lang.reflect.Field.getShort(java.lang.Object) - TestField x = new TestField(); - Field f = null; - short val = 0; - ; - try { - f = x.getClass().getDeclaredField("shortField"); - val = f.getShort(x); - } catch (Exception e) { - fail("Exception during getShort test : " + e.getMessage()); - } - assertTrue("Returned incorrect short field value", - val == Short.MAX_VALUE); - - boolean thrown = false; - try { - f = x.getClass().getDeclaredField("booleanField"); - f.getShort(x); - fail("IllegalArgumentException expected but not thrown"); - } catch (IllegalArgumentException ex) { - thrown = true; - } catch (Exception ex) { - fail("IllegalArgumentException expected but not thrown " - + ex.getMessage()); - } - assertTrue("IllegalArgumentException expected but not thrown", thrown); - - thrown = false; - try { - f = x.getClass().getDeclaredField("shortPFField"); - f.getShort(x); - fail("IllegalAccessException expected but not thrown"); - } catch (IllegalAccessException ex) { - thrown = true; - } catch (Exception ex) { - fail("IllegalAccessException expected but not thrown" - + ex.getMessage()); - } - assertTrue("IllegalAccessException expected but not thrown", thrown); - - //Test NPE - thrown = false; - try { - f = x.getClass().getDeclaredField("shortField"); - f.getShort(null); - fail("NullPointerException expected but not thrown"); - } catch (NullPointerException ex) { - thrown = true; - } catch (Exception ex) { - fail("NullPointerException expected but not thrown"); - } - assertTrue("NullPointerException expected but not thrown", thrown); - - //Test no NPE on static field - thrown = false; - try { - f = x.getClass().getDeclaredField("shortSField"); - short staticValue = f.getShort(null); - assertEquals("Wrong value returned", Short.MAX_VALUE, staticValue); - } catch (Exception ex) { - fail("No exception expected "+ ex.getMessage()); - } - } - - /** - * java.lang.reflect.Field#getType() - */ - public void test_getType() { - // Test for method java.lang.Class java.lang.reflect.Field.getType() - TestField x = new TestField(); - Field f = null; - try { - f = x.getClass().getDeclaredField("shortField"); - } catch (Exception e) { - fail("Exception during getType test : " + e.getMessage()); - } - assertTrue("Returned incorrect field type: " + f.getType().toString(), - f.getType().equals(short.class)); - } - - /** - * java.lang.reflect.Field#set(java.lang.Object, java.lang.Object) - */ - public void test_setLjava_lang_ObjectLjava_lang_Object() throws Exception{ - // Test for method void java.lang.reflect.Field.set(java.lang.Object, - // java.lang.Object) - TestField x = new TestField(); - Field f = null; - double val = 0.0; - try { - f = x.getClass().getDeclaredField("doubleField"); - f.set(x, new Double(1.0)); - val = f.getDouble(x); - } catch (Exception e) { - fail("Exception during set test : " + e.getMessage()); - } - assertEquals("Returned incorrect double field value", 1.0, val); - - //test wrong type - boolean thrown = false; - try { - f = x.getClass().getDeclaredField("booleanField"); - f.set(x, new Double(1.0)); - fail("Accessed field of invalid type"); - } catch (IllegalArgumentException ex) { - thrown = true; - } - assertTrue("IllegalArgumentException expected but not thrown", thrown); - - //test not accessible - thrown = false; - try { - f = x.getClass().getDeclaredField("doubleFField"); - assertFalse(f.isAccessible()); - f.set(x, new Double(1.0)); - fail("Accessed inaccessible field"); - } catch (IllegalAccessException ex) { - thrown = true; - } - assertTrue("IllegalAccessException expected but not thrown", thrown); - - //Test NPE - thrown = false; - try { - f = x.getClass().getDeclaredField("booleanField"); - f.set(null, true); - fail("NullPointerException expected but not thrown"); - } catch (NullPointerException ex) { - thrown = true; - } catch (Exception ex) { - fail("NullPointerException expected but not thrown"); - } - assertTrue("NullPointerException expected but not thrown", thrown); - - // Test setting a static field; - f = x.getClass().getDeclaredField("doubleSField"); - f.set(null, new Double(1.0)); - val = f.getDouble(x); - assertEquals("Returned incorrect double field value", 1.0, val); - } - - /** - * java.lang.reflect.Field#setBoolean(java.lang.Object, boolean) - */ - public void test_setBooleanLjava_lang_ObjectZ() throws Exception{ - // Test for method void - // java.lang.reflect.Field.setBoolean(java.lang.Object, boolean) - TestField x = new TestField(); - Field f = null; - boolean val = false; - try { - f = x.getClass().getDeclaredField("booleanField"); - f.setBoolean(x, false); - val = f.getBoolean(x); - } catch (Exception e) { - fail("Exception during setboolean test: " + e.toString()); - } - assertTrue("Returned incorrect float field value", !val); - - //test wrong type - boolean thrown = false; - try { - f = x.getClass().getDeclaredField("doubleField"); - f.setBoolean(x, false); - fail("Accessed field of invalid type"); - } catch (IllegalArgumentException ex) { - thrown = true; - } - assertTrue("IllegalArgumentException expected but not thrown", thrown); - - //test not accessible - thrown = false; - try { - f = x.getClass().getDeclaredField("booleanPFField"); - assertFalse(f.isAccessible()); - f.setBoolean(x, true); - fail("Accessed inaccessible field"); - } catch (IllegalAccessException ex) { - thrown = true; - } - assertTrue("IllegalAccessException expected but not thrown", thrown); - - //Test NPE - thrown = false; - try { - f = x.getClass().getDeclaredField("booleanField"); - f.setBoolean(null, true); - fail("NullPointerException expected but not thrown"); - } catch (NullPointerException ex) { - thrown = true; - } catch (Exception ex) { - fail("NullPointerException expected but not thrown"); - } - assertTrue("NullPointerException expected but not thrown", thrown); - - // Test setting a static field; - f = x.getClass().getDeclaredField("booleanSField"); - f.setBoolean(null, false); - val = f.getBoolean(x); - assertFalse("Returned incorrect boolean field value", val); - } - - /** - * java.lang.reflect.Field#setByte(java.lang.Object, byte) - */ - public void test_setByteLjava_lang_ObjectB() throws Exception{ - // Test for method void - // java.lang.reflect.Field.setByte(java.lang.Object, byte) - TestField x = new TestField(); - Field f = null; - byte val = 0; - try { - f = x.getClass().getDeclaredField("byteField"); - f.setByte(x, (byte) 1); - val = f.getByte(x); - } catch (Exception e) { - fail("Exception during setByte test : " + e.getMessage()); - } - assertEquals("Returned incorrect float field value", 1, val); - - //test wrong type - boolean thrown = false; - try { - f = x.getClass().getDeclaredField("booleanField"); - f.setByte(x, Byte.MIN_VALUE); - fail("Accessed field of invalid type"); - } catch (IllegalArgumentException ex) { - thrown = true; - } - assertTrue("IllegalArgumentException expected but not thrown", thrown); - - //test not accessible - thrown = false; - try { - f = x.getClass().getDeclaredField("bytePFField"); - assertFalse(f.isAccessible()); - f.setByte(x, Byte.MIN_VALUE); - fail("Accessed inaccessible field"); - } catch (IllegalAccessException ex) { - thrown = true; - } - assertTrue("IllegalAccessException expected but not thrown", thrown); - - //Test NPE - thrown = false; - try { - f = x.getClass().getDeclaredField("byteField"); - f.setByte(null, Byte.MIN_VALUE); - fail("NullPointerException expected but not thrown"); - } catch (NullPointerException ex) { - thrown = true; - } catch (Exception ex) { - fail("NullPointerException expected but not thrown"); - } - assertTrue("NullPointerException expected but not thrown", thrown); - - // Test setting a static field; - f = x.getClass().getDeclaredField("byteSField"); - f.setByte(null, Byte.MIN_VALUE); - val = f.getByte(x); - assertEquals("Returned incorrect byte field value", Byte.MIN_VALUE, - val); - } - - /** - * java.lang.reflect.Field#setChar(java.lang.Object, char) - */ - public void test_setCharLjava_lang_ObjectC() throws Exception{ - // Test for method void - // java.lang.reflect.Field.setChar(java.lang.Object, char) - TestField x = new TestField(); - Field f = null; - char val = 0; - try { - f = x.getClass().getDeclaredField("charField"); - f.setChar(x, (char) 1); - val = f.getChar(x); - } catch (Exception e) { - fail("Exception during setChar test : " + e.getMessage()); - } - assertEquals("Returned incorrect float field value", 1, val); - - //test wrong type - boolean thrown = false; - try { - f = x.getClass().getDeclaredField("booleanField"); - f.setChar(x, Character.MIN_VALUE); - fail("Accessed field of invalid type"); - } catch (IllegalArgumentException ex) { - thrown = true; - } - assertTrue("IllegalArgumentException expected but not thrown", thrown); - - //test not accessible - thrown = false; - try { - f = x.getClass().getDeclaredField("charPFField"); - assertFalse(f.isAccessible()); - f.setChar(x, Character.MIN_VALUE); - fail("Accessed inaccessible field"); - } catch (IllegalAccessException ex) { - thrown = true; - } - assertTrue("IllegalAccessException expected but not thrown", thrown); - - //Test NPE - thrown = false; - try { - f = x.getClass().getDeclaredField("charField"); - f.setChar(null, Character.MIN_VALUE); - fail("NullPointerException expected but not thrown"); - } catch (NullPointerException ex) { - thrown = true; - } catch (Exception ex) { - fail("NullPointerException expected but not thrown"); - } - assertTrue("NullPointerException expected but not thrown", thrown); - - // Test setting a static field; - f = x.getClass().getDeclaredField("charSField"); - f.setChar(null, Character.MIN_VALUE); - val = f.getChar(x); - assertEquals("Returned incorrect char field value", - Character.MIN_VALUE, val); - } - - /** - * java.lang.reflect.Field#setDouble(java.lang.Object, double) - */ - public void test_setDoubleLjava_lang_ObjectD() throws Exception{ - // Test for method void - // java.lang.reflect.Field.setDouble(java.lang.Object, double) - TestField x = new TestField(); - Field f = null; - double val = 0.0; - try { - f = x.getClass().getDeclaredField("doubleField"); - f.setDouble(x, Double.MIN_VALUE); - val = f.getDouble(x); - } catch (Exception e) { - fail("Exception during setDouble test: " + e.toString()); - } - assertEquals("Returned incorrect double field value", Double.MIN_VALUE, - val); - - //test wrong type - boolean thrown = false; - try { - f = x.getClass().getDeclaredField("booleanField"); - f.setDouble(x, Double.MIN_VALUE); - fail("Accessed field of invalid type"); - } catch (IllegalArgumentException ex) { - thrown = true; - } - assertTrue("IllegalArgumentException expected but not thrown", thrown); - - //test not accessible - thrown = false; - try { - f = x.getClass().getDeclaredField("doublePFField"); - assertFalse(f.isAccessible()); - f.setDouble(x, Double.MIN_VALUE); - fail("Accessed inaccessible field"); - } catch (IllegalAccessException ex) { - thrown = true; - } - assertTrue("IllegalAccessException expected but not thrown", thrown); - - //Test NPE - thrown = false; - try { - f = x.getClass().getDeclaredField("doubleField"); - f.setDouble(null, Double.MIN_VALUE); - fail("NullPointerException expected but not thrown"); - } catch (NullPointerException ex) { - thrown = true; - } catch (Exception ex) { - fail("NullPointerException expected but not thrown"); - } - assertTrue("NullPointerException expected but not thrown", thrown); - - // Test setting a static field; - f = x.getClass().getDeclaredField("doubleSField"); - f.setDouble(null, Double.MIN_VALUE); - val = f.getDouble(x); - assertEquals("Returned incorrect double field value", - Double.MIN_VALUE, val); - } - - /** - * java.lang.reflect.Field#setFloat(java.lang.Object, float) - */ - public void test_setFloatLjava_lang_ObjectF() throws Exception{ - // Test for method void - // java.lang.reflect.Field.setFloat(java.lang.Object, float) - TestField x = new TestField(); - Field f = null; - float val = 0.0F; - try { - f = x.getClass().getDeclaredField("floatField"); - f.setFloat(x, Float.MIN_VALUE); - val = f.getFloat(x); - } catch (Exception e) { - fail("Exception during setFloat test : " + e.getMessage()); - } - assertEquals("Returned incorrect float field value", Float.MIN_VALUE, - val, 0.0); - - //test wrong type - boolean thrown = false; - try { - f = x.getClass().getDeclaredField("booleanField"); - f.setFloat(x, Float.MIN_VALUE); - fail("Accessed field of invalid type"); - } catch (IllegalArgumentException ex) { - thrown = true; - } - assertTrue("IllegalArgumentException expected but not thrown", thrown); - - //test not accessible - thrown = false; - try { - f = x.getClass().getDeclaredField("floatPFField"); - assertFalse(f.isAccessible()); - f.setFloat(x, Float.MIN_VALUE); - fail("Accessed inaccessible field"); - } catch (IllegalAccessException ex) { - thrown = true; - } - assertTrue("IllegalAccessException expected but not thrown", thrown); - - //Test NPE - thrown = false; - try { - f = x.getClass().getDeclaredField("floatField"); - f.setFloat(null, Float.MIN_VALUE); - fail("NullPointerException expected but not thrown"); - } catch (NullPointerException ex) { - thrown = true; - } catch (Exception ex) { - fail("NullPointerException expected but not thrown"); - } - assertTrue("NullPointerException expected but not thrown", thrown); - - // Test setting a static field; - f = x.getClass().getDeclaredField("floatSField"); - f.setFloat(null, Float.MIN_VALUE); - val = f.getFloat(x); - assertEquals("Returned incorrect float field value", - Float.MIN_VALUE, val); - } - - /** - * java.lang.reflect.Field#setInt(java.lang.Object, int) - */ - public void test_setIntLjava_lang_ObjectI() throws Exception{ - // Test for method void java.lang.reflect.Field.setInt(java.lang.Object, - // int) - TestField x = new TestField(); - Field f = null; - int val = 0; - try { - f = x.getClass().getDeclaredField("intField"); - f.setInt(x, Integer.MIN_VALUE); - val = f.getInt(x); - } catch (Exception e) { - fail("Exception during setInteger test: " + e.toString()); - } - assertEquals("Returned incorrect int field value", Integer.MIN_VALUE, - val); - - // test wrong type - boolean thrown = false; - try { - f = x.getClass().getDeclaredField("booleanField"); - f.setInt(x, Integer.MIN_VALUE); - fail("Accessed field of invalid type"); - } catch (IllegalArgumentException ex) { - thrown = true; - } - assertTrue("IllegalArgumentException expected but not thrown", thrown); - - // test not accessible - thrown = false; - try { - f = x.getClass().getDeclaredField("intPFField"); - assertFalse(f.isAccessible()); - f.setInt(x, Integer.MIN_VALUE); - fail("Accessed inaccessible field"); - } catch (IllegalAccessException ex) { - thrown = true; - } - assertTrue("IllegalAccessException expected but not thrown", thrown); - - // Test NPE - thrown = false; - try { - f = x.getClass().getDeclaredField("intField"); - f.setInt(null, Integer.MIN_VALUE); - fail("NullPointerException expected but not thrown"); - } catch (NullPointerException ex) { - thrown = true; - } catch (Exception ex) { - fail("NullPointerException expected but not thrown"); - } - assertTrue("NullPointerException expected but not thrown", thrown); - - // Test setting a static field; - f = x.getClass().getDeclaredField("intSField"); - f.setInt(null, Integer.MIN_VALUE); - val = f.getInt(x); - assertEquals("Returned incorrect int field value", - Integer.MIN_VALUE, val); - } - - /** - * java.lang.reflect.Field#setLong(java.lang.Object, long) - */ - public void test_setLongLjava_lang_ObjectJ() throws Exception{ - // Test for method void - // java.lang.reflect.Field.setLong(java.lang.Object, long) - TestField x = new TestField(); - Field f = null; - long val = 0L; - try { - f = x.getClass().getDeclaredField("longField"); - f.setLong(x, Long.MIN_VALUE); - val = f.getLong(x); - } catch (Exception e) { - fail("Exception during setLong test : " + e.getMessage()); - } - assertEquals("Returned incorrect long field value", Long.MIN_VALUE, val); - - // test wrong type - boolean thrown = false; - try { - f = x.getClass().getDeclaredField("booleanField"); - f.setLong(x, Long.MIN_VALUE); - fail("Accessed field of invalid type"); - } catch (IllegalArgumentException ex) { - thrown = true; - } - assertTrue("IllegalArgumentException expected but not thrown", thrown); - - // test not accessible - thrown = false; - try { - f = x.getClass().getDeclaredField("longPFField"); - assertFalse(f.isAccessible()); - f.setLong(x, Long.MIN_VALUE); - fail("Accessed inaccessible field"); - } catch (IllegalAccessException ex) { - thrown = true; - } - assertTrue("IllegalAccessException expected but not thrown", thrown); - - // Test NPE - thrown = false; - try { - f = x.getClass().getDeclaredField("longField"); - f.setLong(null, Long.MIN_VALUE); - fail("NullPointerException expected but not thrown"); - } catch (NullPointerException ex) { - thrown = true; - } catch (Exception ex) { - fail("NullPointerException expected but not thrown"); - } - assertTrue("NullPointerException expected but not thrown", thrown); - - // Test setting a static field; - f = x.getClass().getDeclaredField("longSField"); - f.setLong(null, Long.MIN_VALUE); - val = f.getLong(x); - assertEquals("Returned incorrect long field value", - Long.MIN_VALUE, val); - } - - /** - * java.lang.reflect.Field#setShort(java.lang.Object, short) - */ - public void test_setShortLjava_lang_ObjectS() throws Exception{ - // Test for method void - // java.lang.reflect.Field.setShort(java.lang.Object, short) - TestField x = new TestField(); - Field f = null; - short val = 0; - try { - f = x.getClass().getDeclaredField("shortField"); - f.setShort(x, Short.MIN_VALUE); - val = f.getShort(x); - } catch (Exception e) { - fail("Exception during setShort test : " + e.getMessage()); - } - assertEquals("Returned incorrect short field value", Short.MIN_VALUE, - val); - - // test wrong type - boolean thrown = false; - try { - f = x.getClass().getDeclaredField("booleanField"); - f.setShort(x, Short.MIN_VALUE); - fail("Accessed field of invalid type"); - } catch (IllegalArgumentException ex) { - thrown = true; - } - assertTrue("IllegalArgumentException expected but not thrown", thrown); - - // test not accessible - thrown = false; - try { - f = x.getClass().getDeclaredField("shortPFField"); - assertFalse(f.isAccessible()); - f.setShort(x, Short.MIN_VALUE); - fail("Accessed inaccessible field"); - } catch (IllegalAccessException ex) { - thrown = true; - } - assertTrue("IllegalAccessException expected but not thrown", thrown); - - // Test NPE - thrown = false; - try { - f = x.getClass().getDeclaredField("shortField"); - f.setShort(null, Short.MIN_VALUE); - fail("NullPointerException expected but not thrown"); - } catch (NullPointerException ex) { - thrown = true; - } catch (Exception ex) { - fail("NullPointerException expected but not thrown"); - } - assertTrue("NullPointerException expected but not thrown", thrown); - - // Test setting a static field; - f = x.getClass().getDeclaredField("shortSField"); - f.setShort(null, Short.MIN_VALUE); - val = f.getShort(x); - assertEquals("Returned incorrect short field value", - Short.MIN_VALUE, val); - } - - /** - * java.lang.reflect.Field#toString() - */ - public void test_toString() { - // Test for method java.lang.String java.lang.reflect.Field.toString() - Field f = null; - - try { - f = TestField.class.getDeclaredField("x"); - } catch (Exception e) { - fail("Exception getting field : " + e.getMessage()); - } - assertEquals("Field returned incorrect string", - "private static final int tests.api.java.lang.reflect.FieldTest$TestField.x", - f.toString()); - } - - public void test_getDeclaredAnnotations() throws Exception { - Field field = TestClass.class.getField("annotatedField"); - Annotation[] annotations = field.getDeclaredAnnotations(); - assertEquals(2, annotations.length); - - Set<Class<?>> ignoreOrder = new HashSet<Class<?>>(); - ignoreOrder.add(annotations[0].annotationType()); - ignoreOrder.add(annotations[1].annotationType()); - - assertTrue("Missing @AnnotationRuntime0", ignoreOrder - .contains(AnnotationRuntime0.class)); - assertTrue("Missing @AnnotationRuntime1", ignoreOrder - .contains(AnnotationRuntime1.class)); - } - - public void test_isEnumConstant() throws Exception { - Field field = TestEnum.class.getDeclaredField("A"); - assertTrue("Enum constant not recognized", field.isEnumConstant()); - - field = TestEnum.class.getDeclaredField("field"); - assertFalse("Non enum constant wrongly stated as enum constant", field - .isEnumConstant()); - - field = TestClass.class.getDeclaredField("annotatedField"); - assertFalse("Non enum constant wrongly stated as enum constant", field - .isEnumConstant()); - } - - public void test_isSynthetic() throws Exception { - Field[] fields = TestClass.Inner.class.getDeclaredFields(); - assertEquals("Not exactly one field returned", 1, fields.length); - - assertTrue("Enum constant not recognized", fields[0].isSynthetic()); - - Field field = TestEnum.class.getDeclaredField("field"); - assertFalse("Non synthetic field wrongly stated as synthetic", field - .isSynthetic()); - - field = TestClass.class.getDeclaredField("annotatedField"); - assertFalse("Non synthetic field wrongly stated as synthetic", field - .isSynthetic()); - } - - - public void test_getGenericType() throws Exception { - Field field = GenericField.class.getDeclaredField("field"); - Type type = field.getGenericType(); - @SuppressWarnings("unchecked") - TypeVariable typeVar = (TypeVariable) type; - assertEquals("Wrong type name returned", "S", typeVar.getName()); - - Field boundedField = GenericField.class.getDeclaredField("boundedField"); - Type boundedType = boundedField.getGenericType(); - @SuppressWarnings("unchecked") - TypeVariable boundedTypeVar = (TypeVariable) boundedType; - assertEquals("Wrong type name returned", "T", boundedTypeVar.getName()); - assertEquals("More than one bound found", 1, - boundedTypeVar.getBounds().length); - assertEquals("Wrong bound returned", Number.class, - boundedTypeVar.getBounds()[0]); - } - - - public void test_toGenericString() throws Exception { - Field field = GenericField.class.getDeclaredField("field"); - assertEquals("Wrong generic string returned", - "S tests.api.java.lang.reflect.FieldTest$GenericField.field", - field.toGenericString()); - - Field boundedField = GenericField.class - .getDeclaredField("boundedField"); - assertEquals( - "Wrong generic string returned", - "T tests.api.java.lang.reflect.FieldTest$GenericField.boundedField", - boundedField.toGenericString()); - - Field ordinary = GenericField.class.getDeclaredField("intField"); - assertEquals( - "Wrong generic string returned", - "int tests.api.java.lang.reflect.FieldTest$GenericField.intField", - ordinary.toGenericString()); - } - - - public void test_hashCode() throws Exception { - Field field = TestClass.class.getDeclaredField("annotatedField"); - assertEquals("Wrong hashCode returned", field.getName().hashCode() - ^ field.getDeclaringClass().getName().hashCode(), field - .hashCode()); - } - - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - } -} - -class TestAccess { - private static int xxx; -} diff --git a/luni/src/test/java/tests/api/java/lang/reflect/GenericArrayTypeTest.java b/luni/src/test/java/tests/api/java/lang/reflect/GenericArrayTypeTest.java deleted file mode 100644 index e48e584..0000000 --- a/luni/src/test/java/tests/api/java/lang/reflect/GenericArrayTypeTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2008 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 tests.api.java.lang.reflect; - -import java.lang.reflect.Field; -import java.lang.reflect.GenericArrayType; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; - -/** - * Tests generic reflection on arrays with generic or parameterized component types. - */ -public class GenericArrayTypeTest extends GenericReflectionTestsBase { - - static class A<T> { - T[] array; - } - public void testGetGenericComponentType() throws Exception { - @SuppressWarnings("unchecked") - Class<? extends A> clazz = GenericArrayTypeTest.A.class; - Field field = clazz.getDeclaredField("array"); - Type genericType = field.getGenericType(); - assertInstanceOf(GenericArrayType.class, genericType); - Type componentType = ((GenericArrayType) genericType).getGenericComponentType(); - assertEquals(getTypeParameter(clazz), componentType); - assertInstanceOf(TypeVariable.class, componentType); - TypeVariable<?> componentTypeVariable = (TypeVariable<?>) componentType; - assertEquals("T", componentTypeVariable.getName()); - assertEquals(clazz, componentTypeVariable.getGenericDeclaration()); - } - - static class B<T> { - B<T>[] array; - } - public void testParameterizedComponentType() throws Exception { - @SuppressWarnings("unchecked") - Class<? extends B> clazz = GenericArrayTypeTest.B.class; - Field field = clazz.getDeclaredField("array"); - Type genericType = field.getGenericType(); - - assertInstanceOf(GenericArrayType.class, genericType); - GenericArrayType arrayType = (GenericArrayType) genericType; - Type componentType = arrayType.getGenericComponentType(); - assertInstanceOf(ParameterizedType.class, componentType); - ParameterizedType parameteriezdType = (ParameterizedType) componentType; - assertEquals(clazz, parameteriezdType.getRawType()); - assertEquals(clazz.getTypeParameters()[0], parameteriezdType.getActualTypeArguments()[0]); - } -} diff --git a/luni/src/test/java/tests/api/java/lang/reflect/GenericMethodsTests.java b/luni/src/test/java/tests/api/java/lang/reflect/GenericMethodsTests.java deleted file mode 100644 index 0bfc188..0000000 --- a/luni/src/test/java/tests/api/java/lang/reflect/GenericMethodsTests.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (C) 2008 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 tests.api.java.lang.reflect; - - -import java.lang.reflect.Method; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; - - -/** - * Tests unbounded type parameters declared on methods. - */ -public class GenericMethodsTests extends GenericReflectionTestsBase{ - - static class GenericMethods { - - public <T> void noParamNoReturn() {} - - public <T> void paramNoReturn(T param) {} - - @SuppressWarnings("unchecked") - public <T> T noParamReturn() { return (T) new Object(); } - - public <T> T paramReturn(T param) {return param;} - } - - private static Class<? extends GenericMethods> clazz = GenericMethodsTests.GenericMethods.class; - - /** - * Tests that there are no Type Parameters on the Class itself. - */ - public void testGenericMethods() { - assertLenghtZero(clazz.getTypeParameters()); - } - - /** - * Tests whether the specified method declares a type parameter T. - * @param method the method - */ - private void checkTypeParameter(Method method) { - TypeVariable<Method> typeParameter = getTypeParameter(method); - assertEquals("T", typeParameter.getName()); - assertEquals(method, typeParameter.getGenericDeclaration()); - } - - /** - * Tests whether the specified method declares a parameter with the - * type of the type parameter. - * @param method the method - */ - private void checkParameterType(Method method) { - TypeVariable<Method> typeParameter = getTypeParameter(method); - assertLenghtOne(method.getGenericParameterTypes()); - Type genericParameterType = method.getGenericParameterTypes()[0]; - assertEquals(typeParameter, genericParameterType); - assertInstanceOf(TypeVariable.class, genericParameterType); - assertEquals(method, ((TypeVariable<?>) genericParameterType).getGenericDeclaration()); - } - - /** - * Tests whether the type of the return type is the declared type parameter. - * @param method the declaring method - */ - private void checkReturnType(Method method) { - TypeVariable<Method> typeParameter = getTypeParameter(method); - Type genericReturnType = method.getGenericReturnType(); - assertEquals(typeParameter, genericReturnType); - assertInstanceOf(TypeVariable.class, genericReturnType); - assertEquals(method, ((TypeVariable<?>) genericReturnType).getGenericDeclaration()); - } - public void testNoParamNoReturn() throws Exception { - Method method = clazz.getMethod("noParamNoReturn"); - checkTypeParameter(method); - } - - public void testParamNoReturn() throws Exception { - Method method = clazz.getMethod("paramNoReturn", Object.class); - checkTypeParameter(method); - checkParameterType(method); - } - - public void testNoParamReturn() throws Exception { - Method method = clazz.getMethod("noParamReturn"); - checkTypeParameter(method); - assertLenghtZero(method.getGenericParameterTypes()); - checkReturnType(method); - } - public void testParamReturn() throws Exception { - Method method = clazz.getMethod("paramReturn", Object.class); - checkTypeParameter(method); - checkParameterType(method); - checkReturnType(method); - } - public void testIndependencyOfMethodTypeParameters() throws Exception { - Method method0 = clazz.getMethod("paramNoReturn", Object.class); - TypeVariable<Method> typeParameter0 = method0.getTypeParameters()[0]; - - Method method1 = clazz.getMethod("noParamNoReturn"); - TypeVariable<Method> typeParameter1 = method1.getTypeParameters()[0]; - - //Generic method type parameters NAMES are equal - assertEquals(typeParameter0.getName(), typeParameter1.getName()); - //Generic method type PARAMETERS are not equal - assertNotEquals(typeParameter0, typeParameter1); - } -} diff --git a/luni/src/test/java/tests/api/java/lang/reflect/GenericReflectionTestsBase.java b/luni/src/test/java/tests/api/java/lang/reflect/GenericReflectionTestsBase.java deleted file mode 100644 index 095bb72..0000000 --- a/luni/src/test/java/tests/api/java/lang/reflect/GenericReflectionTestsBase.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2008 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 tests.api.java.lang.reflect; - -import java.lang.reflect.Method; -import java.lang.reflect.TypeVariable; - -import junit.framework.TestCase; - -public class GenericReflectionTestsBase extends TestCase{ - - /** - * Returns the type parameter of the declaring method. - * - * @param method - * the declaring method - * @return the type parameter of the method - */ - public TypeVariable<Method> getTypeParameter(Method method) { - TypeVariable<Method>[] typeParameters = method.getTypeParameters(); - assertLenghtOne(typeParameters); - TypeVariable<Method> typeParameter = typeParameters[0]; - return typeParameter; - } - - /** - * Returns the type parameter of the declaring class. - * - * @param method - * the declaring method. - * @return the type parameter of the method. - */ - @SuppressWarnings("unchecked") - public TypeVariable<Class> getTypeParameter(Class<?> clazz) { - TypeVariable[] typeParameters = clazz.getTypeParameters(); - assertLenghtOne(typeParameters); - TypeVariable<Class> typeVariable = typeParameters[0]; - assertEquals(clazz, typeVariable.getGenericDeclaration()); - assertEquals("T", typeVariable.getName()); - return typeVariable; - } - - public static void assertLenghtOne(Object[] array) { - TestCase.assertEquals("Array does NOT contain exactly one element.", 1, array.length); - } - - public static void assertLenghtZero(Object[] array) { - TestCase.assertEquals("Array has more than zero elements.", 0, array.length); - } - - public static void assertInstanceOf(Class<?> expectedClass, Object actual) { - TestCase.assertTrue(actual.getClass().getName() + " is not instance of :" + expectedClass.getName(), expectedClass - .isInstance(actual)); - } - - public static void assertNotEquals(Object expected, Object actual) { - TestCase.assertFalse(actual.toString() + " has not to be equal to " + expected.toString(), expected.equals(actual)); - } - -} diff --git a/luni/src/test/java/tests/api/java/lang/reflect/GenericSignatureFormatErrorTest.java b/luni/src/test/java/tests/api/java/lang/reflect/GenericSignatureFormatErrorTest.java deleted file mode 100644 index 954073c..0000000 --- a/luni/src/test/java/tests/api/java/lang/reflect/GenericSignatureFormatErrorTest.java +++ /dev/null @@ -1,101 +0,0 @@ -package tests.api.java.lang.reflect; - -import dalvik.annotation.AndroidOnly; -import dalvik.annotation.SideEffect; -import dalvik.system.DexFile; - -import junit.framework.TestCase; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.reflect.GenericSignatureFormatError; -import java.lang.reflect.TypeVariable; - -import tests.support.Support_ClassLoader; - -public class GenericSignatureFormatErrorTest extends TestCase{ - - public void test_Constructor() { - assertNotNull(new GenericSignatureFormatError()); - } - - public void test_readResource() throws Exception { - File tf = File.createTempFile("classes", ".dex"); - // System.out.println("GenericSignatureFormatErrorTest:" - // +tf.getAbsolutePath()+", canRead: "+tf.canRead() - // +", canWrite: "+tf.canWrite()); - InputStream is = this.getClass().getResourceAsStream("dex1.bytes"); - assertNotNull(is); - } - - - @AndroidOnly("Uses Android specific class dalvik.system.DexFile " + - "for loading classes.") - @SideEffect("strange issue (exception: 'could not open dex file', " + - "dalvikvm: 'waitpid failed' log msg - only occurs when @SideEffect is removed " + - "and this test is run via running tests.luni.AllTestsLang TestSuite") - public void test_signatureFormatError() throws Exception { - /* - * dex1.bytes is a jar file with a classes.dex in it. - * the classes.dex was javac'ed, dx'ed and patched - * with the following java file: - * - * package demo; - * public class HelloWorld<U> { - * public HelloWorld(U t) {} - * } - * - * patch: - * the string constant (class generics signature string) - * "<U:" was changed to "<<:" - * - */ - - File tf = File.createTempFile("classes", ".dex"); - // System.out.println("GenericSignatureFormatErrorTest:" + - // tf.getAbsolutePath() + ", canRead: " + tf.canRead() + - // ", canWrite: "+tf.canWrite()); - InputStream is = this.getClass().getResourceAsStream("dex1.bytes"); - assertNotNull(is); - OutputStream fos = new FileOutputStream(tf); - copy(is, fos); - fos.flush(); - fos.close(); - - - // class signature string "<U:" was changed to "<<:" - //System.out.println("file length:"+tf.length()); - try { - // Was: - // DexFile df = new DexFile(tf); - // Class clazz = df.loadClass("demo/HelloWorld", this.getClass().getClassLoader()); - - ClassLoader cl = Support_ClassLoader.getInstance(tf.toURL(), - getClass().getClassLoader()); - - Class clazz = cl.loadClass("demo/HelloWorld"); - TypeVariable[] tvs = clazz.getTypeParameters(); - fail("expecting a GenericSignatureFormatError"); - // for (TypeVariable tv : tvs) { - // System.out.println("tv:"+tv.toString()); - // } - } catch (GenericSignatureFormatError gsfe) { - // expected - } - } - - private void copy(InputStream is, OutputStream os) { - try { - int b; - while ((b = is.read()) != -1) { - os.write(b); - } - is.close(); - } catch (IOException ex) { - throw new RuntimeException("io error", ex); - } - } -} diff --git a/luni/src/test/java/tests/api/java/lang/reflect/InvocationTargetExceptionTest.java b/luni/src/test/java/tests/api/java/lang/reflect/InvocationTargetExceptionTest.java deleted file mode 100644 index 5e699a9..0000000 --- a/luni/src/test/java/tests/api/java/lang/reflect/InvocationTargetExceptionTest.java +++ /dev/null @@ -1,305 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.lang.reflect; - -import java.io.ByteArrayOutputStream; -import java.io.CharArrayWriter; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -public class InvocationTargetExceptionTest extends junit.framework.TestCase { - - static class TestMethod { - public TestMethod() { - } - - public void voidMethod() throws IllegalArgumentException { - } - - public void parmTest(int x, short y, String s, boolean bool, Object o, - long l, byte b, char c, double d, float f) { - } - - public int intMethod() { - return 1; - } - - public static final void printTest(int x, short y, String s, - boolean bool, Object o, long l, byte b, char c, double d, - float f) { - } - - public double doubleMethod() { - return 1.0; - } - - public short shortMethod() { - return (short) 1; - } - - public byte byteMethod() { - return (byte) 1; - } - - public float floatMethod() { - return 1.0f; - } - - public long longMethod() { - return 1l; - } - - public char charMethod() { - return 'T'; - } - - public Object objectMethod() { - return new Object(); - } - - private static void prstatic() { - } - - public static void pustatic() { - } - - public static synchronized void pustatsynch() { - } - - public static int invokeStaticTest() { - return 1; - } - - public int invokeInstanceTest() { - return 1; - } - - private int privateInvokeTest() { - return 1; - } - - public int invokeExceptionTest() throws NullPointerException { - throw new NullPointerException(); - } - - public static synchronized native void pustatsynchnat(); - - } - - abstract class AbstractTestMethod { - public abstract void puabs(); - } - - class SubInvocationTargetException extends InvocationTargetException {} - - /** - * java.lang.reflect.InvocationTargetException#InvocationTargetException() - */ - public void test_Constructor() throws Exception { - Constructor<InvocationTargetException> ctor = InvocationTargetException.class - .getDeclaredConstructor(); - assertNotNull("Parameterless constructor does not exist.", ctor); - assertTrue("Constructor is not protected", Modifier.isProtected(ctor - .getModifiers())); - //create an instance of a subtype using this constructor - SubInvocationTargetException subException = new SubInvocationTargetException(); - } - - /** - * java.lang.reflect.InvocationTargetException#InvocationTargetException(java.lang.Throwable) - */ - public void test_ConstructorLjava_lang_Throwable() { - // Test for method - // java.lang.reflect.InvocationTargetException(java.lang.Throwable) - try { - Method mth = TestMethod.class.getDeclaredMethod( - "invokeExceptionTest", new Class[0]); - Object[] args = { Object.class }; - Object ret = mth.invoke(new TestMethod(), new Object[0]); - } catch (InvocationTargetException e) { - // Correct behaviour - return; - } catch (NoSuchMethodException e) { - } catch (IllegalAccessException e) { - } - fail("Failed to throw exception"); - } - - /** - * java.lang.reflect.InvocationTargetException#InvocationTargetException(java.lang.Throwable, - * java.lang.String) - */ - public void test_ConstructorLjava_lang_ThrowableLjava_lang_String() { - // Test for method - // java.lang.reflect.InvocationTargetException(java.lang.Throwable, - // java.lang.String) - try { - Method mth = TestMethod.class.getDeclaredMethod( - "invokeExceptionTest", new Class[0]); - Object[] args = { Object.class }; - Object ret = mth.invoke(new TestMethod(), new Object[0]); - } catch (InvocationTargetException e) { - // Correct behaviour - return; - } catch (NoSuchMethodException e) { - ; - } catch (IllegalAccessException e) { - } - fail("Failed to throw exception"); - } - - /** - * java.lang.reflect.InvocationTargetException#getTargetException() - */ - public void test_getTargetException() { - // Test for method java.lang.Throwable - // java.lang.reflect.InvocationTargetException.getTargetException() - try { - Method mth = TestMethod.class.getDeclaredMethod( - "invokeExceptionTest", new Class[0]); - Object[] args = { Object.class }; - Object ret = mth.invoke(new TestMethod(), new Object[0]); - } catch (InvocationTargetException e) { - // Correct behaviour - assertTrue("Returned incorrect target exception", e - .getTargetException() instanceof NullPointerException); - return; - } catch (Exception e) { - fail("Exception during constructor test : " + e.getMessage()); - } - fail("Failed to throw exception"); - } - - /** - * java.lang.reflect.InvocationTargetException#getCause() - */ - public void test_getCause() { - // java.lang.reflect.InvocationTargetException.getCause() - try { - Method mth = TestMethod.class.getDeclaredMethod( - "invokeExceptionTest", new Class[0]); - Object[] args = {Object.class}; - Object ret = mth.invoke(new TestMethod(), new Object[0]); - } catch (InvocationTargetException e) { - // Correct behaviour - assertTrue("Returned incorrect cause", - e.getCause() instanceof NullPointerException); - return; - } catch (Exception e) { - fail("Exception during InvocationTargetException test : " - + e.getMessage()); - } - fail("Failed to throw exception"); - } - - /** - * java.lang.reflect.InvocationTargetException#printStackTrace() - */ - public void test_printStackTrace() { - // Test for method void - // java.lang.reflect.InvocationTargetException.printStackTrace() - try { - ByteArrayOutputStream bao = new ByteArrayOutputStream(); - PrintStream ps = new PrintStream(bao); - PrintStream oldErr = System.err; - System.setErr(ps); - InvocationTargetException ite = new InvocationTargetException(null); - ite.printStackTrace(); - System.setErr(oldErr); - - String s = new String(bao.toByteArray()); - - assertTrue("Incorrect Stack trace: " + s, s != null - && s.length() > 300); - } catch (Exception e) { - fail("printStackTrace() caused exception : " + e.getMessage()); - } - } - - /** - * java.lang.reflect.InvocationTargetException#printStackTrace(java.io.PrintStream) - */ - public void test_printStackTraceLjava_io_PrintStream() { - // Test for method void - // java.lang.reflect.InvocationTargetException.printStackTrace(java.io.PrintStream) - assertTrue("Tested via test_printStackTrace().", true); - ByteArrayOutputStream bao = new ByteArrayOutputStream(); - PrintStream ps = new PrintStream(bao); - InvocationTargetException ite = new InvocationTargetException( - new InvocationTargetException(null)); - ite.printStackTrace(ps); - String s = bao.toString(); - assertTrue("printStackTrace failed." + s.length(), s != null - && s.length() > 400); - } - - /** - * java.lang.reflect.InvocationTargetException#printStackTrace(java.io.PrintWriter) - */ - public void test_printStackTraceLjava_io_PrintWriter() { - // Test for method void - // java.lang.reflect.InvocationTargetException.printStackTrace(java.io.PrintWriter) - try { - PrintWriter pw; - InvocationTargetException ite; - String s; - CharArrayWriter caw = new CharArrayWriter(); - pw = new PrintWriter(caw); - ite = new InvocationTargetException(new InvocationTargetException( - null)); - ite.printStackTrace(pw); - - s = caw.toString(); - assertTrue("printStackTrace failed." + s.length(), s != null - && s.length() > 400); - pw.close(); - - ByteArrayOutputStream bao = new ByteArrayOutputStream(); - pw = new PrintWriter(bao); - ite = new InvocationTargetException(new InvocationTargetException( - null)); - ite.printStackTrace(pw); - - pw.flush(); // Test will fail if this line removed. - s = bao.toString(); - assertTrue("printStackTrace failed." + s.length(), s != null - && s.length() > 400); - - } catch (Exception e) { - fail("Exception during test : " + e.getMessage()); - } - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/lang/reflect/MalformedParameterizedTypeExceptionTests.java b/luni/src/test/java/tests/api/java/lang/reflect/MalformedParameterizedTypeExceptionTests.java deleted file mode 100644 index f86403d..0000000 --- a/luni/src/test/java/tests/api/java/lang/reflect/MalformedParameterizedTypeExceptionTests.java +++ /dev/null @@ -1,21 +0,0 @@ -package tests.api.java.lang.reflect; - -import java.lang.reflect.Constructor; -import java.lang.reflect.MalformedParameterizedTypeException; -import java.lang.reflect.Modifier; - -public class MalformedParameterizedTypeExceptionTests extends junit.framework.TestCase { - - /** - * java.lang.reflect.MalformedParameterizedTypeException#MalformedParameterizedTypeException() - */ - public void test_Constructor() throws Exception { - Constructor<MalformedParameterizedTypeException> ctor = MalformedParameterizedTypeException.class - .getDeclaredConstructor(); - assertNotNull("Parameterless constructor does not exist.", ctor); - assertTrue("Constructor is not protected", Modifier.isPublic(ctor - .getModifiers())); - assertNotNull(ctor.newInstance()); - } - -} diff --git a/luni/src/test/java/tests/api/java/lang/reflect/MethodTest.java b/luni/src/test/java/tests/api/java/lang/reflect/MethodTest.java deleted file mode 100644 index e8288d6..0000000 --- a/luni/src/test/java/tests/api/java/lang/reflect/MethodTest.java +++ /dev/null @@ -1,881 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.lang.reflect; - -import java.lang.annotation.Annotation; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.util.HashSet; -import java.util.Set; - -public class MethodTest extends junit.framework.TestCase { - - static class TestMethod { - public TestMethod() { - } - - public void voidMethod() throws IllegalArgumentException { - } - - public void parmTest(int x, short y, String s, boolean bool, Object o, - long l, byte b, char c, double d, float f) { - } - - public int intMethod() { - return 1; - } - - public static final void printTest(int x, short y, String s, - boolean bool, Object o, long l, byte b, char c, double d, - float f) { - } - - public double doubleMethod() { - return 1.0; - } - - public short shortMethod() { - return (short) 1; - } - - public byte byteMethod() { - return (byte) 1; - } - - public float floatMethod() { - return 1.0f; - } - - public long longMethod() { - return 1l; - } - - public char charMethod() { - return 'T'; - } - - public Object objectMethod() { - return new Object(); - } - - private static void prstatic() { - } - - public static void pustatic() { - } - - public static synchronized void pustatsynch() { - } - - public static int invokeStaticTest() { - return 1; - } - - public int invokeInstanceTest() { - return 1; - } - - private int privateInvokeTest() { - return 1; - } - - public int invokeExceptionTest() throws NullPointerException { - throw new NullPointerException(); - } - - public static synchronized native void pustatsynchnat(); - - public void publicVoidVarargs(Object... param){} - public void publicVoidArray(Object[] param){} - - public void annotatedParameter(@TestAnno @Deprecated int a, - @Deprecated int b, int c) { - } - - @Deprecated - @TestAnno - public void annotatedMethod(){} - - public void hashCodeTest(int i){} - public void hashCodeTest(String s){} - - public void invokeCastTest1(byte param) { - } - - public void invokeCastTest1(short param) { - } - - public void invokeCastTest1(int param) { - } - - public void invokeCastTest1(long param) { - } - - public void invokeCastTest1(float param) { - } - - public void invokeCastTest1(double param) { - } - - public void invokeCastTest1(char param) { - } - - public void invokeCastTest1(boolean param) { - } - } - - @Retention(RetentionPolicy.RUNTIME) - @Target({ElementType.PARAMETER, ElementType.METHOD}) - public static @interface TestAnno{ - public static final String DEFAULT_VALUE = "DEFAULT_VALUE"; - - String value() default DEFAULT_VALUE; - } - - abstract class AbstractTestMethod { - public abstract void puabs(); - } - - class TestMethodSub extends TestMethod { - public int invokeInstanceTest() { - return 0; - } - } - - static interface IBrigeTest<T>{ - T m(); - } - - static class BrigeTest implements IBrigeTest<String> { - public String m(){ return null; } - } - - static class ExceptionTest<T extends Exception>{ - @SuppressWarnings("unused") - void exceptionTest() throws T{} - } - - static class GenericReturnType<T> { - T returnGeneric(){return null;} - } - - static class GenericString<T> { - public static final String GENERIC = - "T tests.api.java.lang.reflect.MethodTest$GenericString.genericString(T)"; - T genericString(T t) { - return null; - } - } - - /** - * java.lang.reflect.Method#equals(java.lang.Object) - */ - public void test_equalsLjava_lang_Object() { - // Test for method boolean - // java.lang.reflect.Method.equals(java.lang.Object) - - Method m1 = null, m2 = null; - try { - m1 = TestMethod.class.getMethod("invokeInstanceTest", new Class[0]); - m2 = TestMethodSub.class.getMethod("invokeInstanceTest", - new Class[0]); - } catch (Exception e) { - fail("Exception during equals test : " + e.getMessage()); - } - assertTrue("Overriden method returned equal", !m1.equals(m2)); - assertTrue("Same method returned not-equal", m1.equals(m1)); - try { - m1 = TestMethod.class.getMethod("invokeStaticTest", new Class[0]); - m2 = TestMethodSub.class - .getMethod("invokeStaticTest", new Class[0]); - } catch (Exception e) { - fail("Exception during equals test : " + e.getMessage()); - } - assertTrue("Inherited method returned not-equal", m1.equals(m2)); - } - - /** - * java.lang.Class#getMethod(java.lang.String, java.lang.Class[]) - */ - public void test_getMethod() throws NoSuchMethodException, SecurityException { - // Check that getMethod treats null parameterTypes the same as an empty array. - Method m1 = TestMethod.class.getMethod("invokeInstanceTest", new Class[0]); - Method m2 = TestMethod.class.getMethod("invokeInstanceTest", (Class[]) null); - assertEquals(m1, m2); - } - - /** - * java.lang.Class#getDeclaredMethod(java.lang.String, java.lang.Class[]) - */ - public void test_getDeclaredMethod() throws NoSuchMethodException, SecurityException { - // Check that getDeclaredMethod treats null parameterTypes the same as an empty array. - Method m1 = TestMethod.class.getDeclaredMethod("invokeInstanceTest", new Class[0]); - Method m2 = TestMethod.class.getDeclaredMethod("invokeInstanceTest", (Class[]) null); - assertEquals(m1, m2); - } - - /** - * java.lang.reflect.Method#getDeclaringClass() - */ - public void test_getDeclaringClass() { - // Test for method java.lang.Class - // java.lang.reflect.Method.getDeclaringClass() - - Method[] mths; - - try { - mths = TestMethod.class.getDeclaredMethods(); - assertTrue("Returned incorrect declaring class: " - + mths[0].getDeclaringClass().toString(), mths[0] - .getDeclaringClass().equals(TestMethod.class)); - } catch (Exception e) { - fail("Exception during getDeclaringClass test: " - + e.toString()); - } - } - - /** - * java.lang.reflect.Method#getExceptionTypes() - */ - public void test_getExceptionTypes() { - // Test for method java.lang.Class [] - // java.lang.reflect.Method.getExceptionTypes() - - try { - Method mth = TestMethod.class.getMethod("voidMethod", new Class[0]); - Class[] ex = mth.getExceptionTypes(); - assertEquals("Returned incorrect number of exceptions", - 1, ex.length); - assertTrue("Returned incorrect exception type", ex[0] - .equals(IllegalArgumentException.class)); - mth = TestMethod.class.getMethod("intMethod", new Class[0]); - ex = mth.getExceptionTypes(); - assertEquals("Returned incorrect number of exceptions", - 0, ex.length); - } catch (Exception e) { - fail("Exception during getExceptionTypes: " + e.toString()); - } - - } - - /** - * java.lang.reflect.Method#getModifiers() - */ - public void test_getModifiers() { - // Test for method int java.lang.reflect.Method.getModifiers() - - Class cl = TestMethod.class; - int mods = 0; - Method mth = null; - int mask = 0; - try { - mth = cl.getMethod("pustatic", new Class[0]); - mods = mth.getModifiers(); - } catch (Exception e) { - fail("Exception during getModfiers test: " + e.toString()); - } - mask = Modifier.PUBLIC | Modifier.STATIC; - assertTrue("Incorrect modifiers returned", (mods | mask) == mask); - try { - mth = cl.getDeclaredMethod("prstatic", new Class[0]); - mods = mth.getModifiers(); - } catch (Exception e) { - fail("Exception during getModfiers test: " + e.toString()); - } - mask = Modifier.PRIVATE | Modifier.STATIC; - assertTrue("Incorrect modifiers returned", (mods | mask) == mask); - try { - mth = cl.getDeclaredMethod("pustatsynch", new Class[0]); - mods = mth.getModifiers(); - } catch (Exception e) { - fail("Exception during getModfiers test: " + e.toString()); - } - mask = (Modifier.PUBLIC | Modifier.STATIC) | Modifier.SYNCHRONIZED; - assertTrue("Incorrect modifiers returned", (mods | mask) == mask); - try { - mth = cl.getDeclaredMethod("pustatsynchnat", new Class[0]); - mods = mth.getModifiers(); - } catch (Exception e) { - fail("Exception during getModfiers test: " + e.toString()); - } - mask = ((Modifier.PUBLIC | Modifier.STATIC) | Modifier.SYNCHRONIZED) - | Modifier.NATIVE; - assertTrue("Incorrect modifiers returned", (mods | mask) == mask); - cl = AbstractTestMethod.class; - try { - mth = cl.getDeclaredMethod("puabs", new Class[0]); - mods = mth.getModifiers(); - } catch (Exception e) { - fail("Exception during getModfiers test: " + e.toString()); - } - mask = Modifier.PUBLIC | Modifier.ABSTRACT; - assertTrue("Incorrect modifiers returned", (mods | mask) == mask); - } - - /** - * java.lang.reflect.Method#getName() - */ - public void test_getName() { - // Test for method java.lang.String java.lang.reflect.Method.getName() - Method mth = null; - try { - mth = TestMethod.class.getMethod("voidMethod", new Class[0]); - } catch (Exception e) { - fail("Exception during getMethodName(): " + e.toString()); - } - assertEquals("Returned incorrect method name", - "voidMethod", mth.getName()); - } - - /** - * java.lang.reflect.Method#isVarArgs() - */ - public void test_isVarArgs() throws Exception { - Method mth = TestMethod.class.getMethod("publicVoidVarargs", - Object[].class); - assertTrue("Varargs method stated as non vararg.", mth.isVarArgs()); - - mth = TestMethod.class.getDeclaredMethod("publicVoidArray", - Object[].class); - assertFalse("Non varargs method stated as vararg.", mth.isVarArgs()); - } - - /** - * java.lang.reflect.Method#isBridge() - */ - public void test_isBridge() throws Exception { - Method[] declaredMethods = BrigeTest.class.getDeclaredMethods(); - assertEquals("Bridge method not generated.", 2, declaredMethods.length); - boolean foundBridgeMethod = false; - for (Method method : declaredMethods) { - if (method.getReturnType().equals(Object.class)) { - assertTrue("Bridge method not stated as bridge.", method - .isBridge()); - foundBridgeMethod = true; - } - } - assertTrue("Bridge method not found.", foundBridgeMethod); - } - - /** - * java.lang.reflect.Method#isSynthetic() - */ - public void test_isSynthetic() throws Exception { - Method[] declaredMethods = BrigeTest.class.getDeclaredMethods(); - assertEquals("Synthetic method not generated.", 2, - declaredMethods.length); - boolean foundSyntheticMethod = false; - for (Method method : declaredMethods) { - if (method.getReturnType().equals(Object.class)) { - assertTrue("Synthetic method not stated as synthetic.", method - .isSynthetic()); - foundSyntheticMethod = true; - } - } - assertTrue("Synthetic method not found.", foundSyntheticMethod); - } - /** - * java.lang.reflect.Method#getParameterAnnotations() - */ - public void test_getParameterAnnotations() throws Exception { - Method method = TestMethod.class.getDeclaredMethod( - "annotatedParameter", new Class[] { - int.class, int.class, int.class}); - Annotation[][] annotations = method.getParameterAnnotations(); - assertEquals(3, annotations.length); - assertEquals( - "Wrong number of annotations returned for first parameter", 2, - annotations[0].length); - Set<Class<?>> annotationSet = new HashSet<Class<?>>(); - annotationSet.add(annotations[0][0].annotationType()); - annotationSet.add(annotations[0][1].annotationType()); - assertTrue("Missing TestAnno annotation", annotationSet - .contains(TestAnno.class)); - assertTrue("Missing Deprecated annotation", annotationSet - .contains(Deprecated.class)); - - assertEquals( - "Wrong number of annotations returned for second parameter", - 1, annotations[1].length); - annotationSet = new HashSet<Class<?>>(); - annotationSet.add(annotations[1][0].annotationType()); - assertTrue("Missing Deprecated annotation", annotationSet - .contains(Deprecated.class)); - assertEquals( - "Wrong number of annotations returned for third parameter", 0, - annotations[2].length); - } - - /** - * java.lang.reflect.Method#getDeclaredAnnotations() - */ - public void test_getDeclaredAnnotations() throws Exception { - Method method = TestMethod.class.getDeclaredMethod("annotatedMethod"); - Annotation[] declaredAnnotations = method.getDeclaredAnnotations(); - assertEquals(2, declaredAnnotations.length); - - Set<Class<?>> annotationSet = new HashSet<Class<?>>(); - annotationSet.add(declaredAnnotations[0].annotationType()); - annotationSet.add(declaredAnnotations[1].annotationType()); - assertTrue("Missing TestAnno annotation", annotationSet - .contains(TestAnno.class)); - assertTrue("Missing Deprecated annotation", annotationSet - .contains(Deprecated.class)); - } - - /** - * java.lang.reflect.Method#getDefaultValue() - */ - public void test_getDefaultValue() throws Exception { - Method method = TestAnno.class.getDeclaredMethod("value"); - assertEquals("Wrong default value returned", TestAnno.DEFAULT_VALUE, - method.getDefaultValue()); - } - - /** - * java.lang.reflect.Method#getDefaultValue() - */ - public void test_getGenericExceptionTypes() throws Exception { - Method method = ExceptionTest.class.getDeclaredMethod("exceptionTest"); - Type[] genericExceptionTypes = method.getGenericExceptionTypes(); - assertEquals(1, genericExceptionTypes.length); - assertTrue(genericExceptionTypes[0] instanceof TypeVariable<?>); - @SuppressWarnings("unchecked") - TypeVariable<Class<ExceptionTest<?>>> tv = - (TypeVariable<Class<ExceptionTest<?>>>) genericExceptionTypes[0]; - assertEquals("T", tv.getName()); - } - - /** - * java.lang.reflect.Method#getGenericReturnType() - */ - public void test_getGenericReturnType() throws Exception { - Method method = GenericReturnType.class - .getDeclaredMethod("returnGeneric"); - Type returnType = method.getGenericReturnType(); - assertNotNull("getGenericReturnType returned null", returnType); - assertTrue(returnType instanceof TypeVariable<?>); - @SuppressWarnings("unchecked") - TypeVariable<Class<ExceptionTest<?>>> tv = - (TypeVariable<Class<ExceptionTest<?>>>) returnType; - assertEquals("T", tv.getName()); - } - - - /** - * java.lang.reflect.Method#toGenericString() - */ - public void test_toGenericString() throws Exception { - Method method = GenericString.class.getDeclaredMethod("genericString", - Object.class); - assertEquals("Wrong generic String returned", GenericString.GENERIC, - method.toGenericString()); - } - - - - - - - /** - * java.lang.reflect.Method#hashCode() - */ - public void test_hashCode() throws Exception { - Method mth0 = TestMethod.class.getMethod("hashCodeTest", String.class); - Method mth1 = TestMethod.class.getDeclaredMethod("hashCodeTest", - int.class); - assertEquals("Methods with same name did not return same hashCode.", - mth0.hashCode(), mth1.hashCode()); - } - - /** - * java.lang.reflect.Method#getParameterTypes() - */ - public void test_getParameterTypes() { - // Test for method java.lang.Class [] - // java.lang.reflect.Method.getParameterTypes() - Class cl = TestMethod.class; - Method mth = null; - Class[] parms = null; - Method[] methods = null; - Class[] plist = { int.class, short.class, String.class, boolean.class, - Object.class, long.class, byte.class, char.class, double.class, - float.class }; - try { - mth = cl.getMethod("voidMethod", new Class[0]); - parms = mth.getParameterTypes(); - } catch (Exception e) { - fail("Exception during getParameterTypes test: " - + e.toString()); - } - assertEquals("Returned incorrect parameterTypes", 0, parms.length); - try { - mth = cl.getMethod("parmTest", plist); - parms = mth.getParameterTypes(); - } catch (Exception e) { - fail("Exception during getParameterTypes test: " - + e.toString()); - } - assertTrue("Invalid number of parameters returned", - plist.length == parms.length); - for (int i = 0; i < plist.length; i++) - assertTrue("Incorrect parameter returned", plist[i] - .equals(parms[i])); - - // Test same method. but this time pull it from the list of methods - // rather than asking for it explicitly - methods = cl.getDeclaredMethods(); - - int i; - for (i = 0; i < methods.length; i++) - if (methods[i].getName().equals("parmTest")) { - mth = methods[i]; - i = methods.length + 1; - } - if (i < methods.length) { - parms = mth.getParameterTypes(); - assertTrue("Incorrect number of parameters returned", - parms.length == plist.length); - for (i = 0; i < plist.length; i++) - assertTrue("Incorrect parameter returned", plist[i] - .equals(parms[i])); - } - } - - /** - * java.lang.reflect.Method#getReturnType() - */ - public void test_getReturnType() { - // Test for method java.lang.Class - // java.lang.reflect.Method.getReturnType() - Class cl = TestMethod.class; - Method mth = null; - try { - mth = cl.getMethod("charMethod", new Class[0]); - } catch (Exception e) { - fail("Exception during getReturnType test : " + e.getMessage()); - } - assertTrue("Gave incorrect returne type, wanted char", mth - .getReturnType().equals(char.class)); - try { - mth = cl.getMethod("longMethod", new Class[0]); - } catch (Exception e) { - fail("Exception during getReturnType test : " + e.getMessage()); - } - assertTrue("Gave incorrect returne type, wanted long", mth - .getReturnType().equals(long.class)); - try { - mth = cl.getMethod("shortMethod", new Class[0]); - } catch (Exception e) { - fail("Exception during getReturnType test : " + e.getMessage()); - } - assertTrue("Gave incorrect returne type, wanted short", mth - .getReturnType().equals(short.class)); - try { - mth = cl.getMethod("intMethod", new Class[0]); - } catch (Exception e) { - fail("Exception during getReturnType test : " + e.getMessage()); - } - assertTrue("Gave incorrect returne type, wanted int: " - + mth.getReturnType(), mth.getReturnType().equals(int.class)); - try { - mth = cl.getMethod("doubleMethod", new Class[0]); - } catch (Exception e) { - fail("Exception during getReturnType test : " + e.getMessage()); - } - assertTrue("Gave incorrect returne type, wanted double", mth - .getReturnType().equals(double.class)); - try { - mth = cl.getMethod("byteMethod", new Class[0]); - } catch (Exception e) { - fail("Exception during getReturnType test : " + e.getMessage()); - } - assertTrue("Gave incorrect returne type, wanted byte", mth - .getReturnType().equals(byte.class)); - try { - mth = cl.getMethod("byteMethod", new Class[0]); - } catch (Exception e) { - fail("Exception during getReturnType test:" + e.toString()); - } - assertTrue("Gave incorrect returne type, wanted byte", mth - .getReturnType().equals(byte.class)); - try { - mth = cl.getMethod("objectMethod", new Class[0]); - } catch (Exception e) { - fail("Exception during getReturnType test : " + e.getMessage()); - } - assertTrue("Gave incorrect returne type, wanted Object", mth - .getReturnType().equals(Object.class)); - - try { - mth = cl.getMethod("voidMethod", new Class[0]); - } catch (Exception e) { - fail("Exception during getReturnType test : " + e.getMessage()); - } - assertTrue("Gave incorrect returne type, wanted void", mth - .getReturnType().equals(void.class)); - } - - /** - * java.lang.reflect.Method#invoke(java.lang.Object, - * java.lang.Object[]) - */ - public void test_invokeLjava_lang_Object$Ljava_lang_Object() throws Exception{ - // Test for method java.lang.Object - // java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object - // []) - Class cl = TestMethod.class; - Class[] dcl = new Class[0]; - - // Get and invoke a static method - Method mth = cl.getDeclaredMethod("invokeStaticTest", dcl); - Object ret = mth.invoke(null, new Object[0]); - assertEquals("Invoke returned incorrect value", 1, ((Integer) ret) - .intValue()); - - // Get and invoke an instance method - mth = cl.getDeclaredMethod("invokeInstanceTest", dcl); - ret = mth.invoke(new TestMethod(), new Object[0]); - assertEquals("Invoke returned incorrect value", 1, ((Integer) ret) - .intValue()); - - // Get and attempt to invoke a private method - mth = cl.getDeclaredMethod("privateInvokeTest", dcl); - try { - ret = mth.invoke(new TestMethod(), new Object[0]); - } catch (IllegalAccessException e) { - // Correct behaviour - } catch (Exception e) { - fail("Exception during invoke test : " + e.getMessage()); - } - // Generate an IllegalArgumentException - mth = cl.getDeclaredMethod("invokeInstanceTest", dcl); - - try { - Object[] args = { Object.class }; - ret = mth.invoke(new TestMethod(), args); - } catch (IllegalArgumentException e) { - // Correct behaviour - } catch (Exception e) { - fail("Exception during invoke test : " + e.getMessage()); - } - - // Generate a NullPointerException - mth = cl.getDeclaredMethod("invokeInstanceTest", dcl); - - try { - ret = mth.invoke(null, new Object[0]); - } catch (NullPointerException e) { - // Correct behaviour - } catch (Exception e) { - fail("Exception during invoke test : " + e.getMessage()); - } - - // Generate an InvocationTargetException - mth = cl.getDeclaredMethod("invokeExceptionTest", dcl); - try { - ret = mth.invoke(new TestMethod(), new Object[0]); - } catch (InvocationTargetException e) { - // Correct behaviour - } catch (Exception e) { - fail("Exception during invoke test : " + e.getMessage()); - } - - TestMethod testMethod = new TestMethod(); - Method methods[] = cl.getMethods(); - for (int i = 0; i < methods.length; i++) { - if (methods[i].getName().startsWith("invokeCastTest1")) { - Class param = methods[i].getParameterTypes()[0]; - - try { - methods[i].invoke(testMethod, new Object[] { new Byte( - (byte) 1) }); - assertTrue("invalid invoke with Byte: " + methods[i], - param == Byte.TYPE || param == Short.TYPE - || param == Integer.TYPE - || param == Long.TYPE - || param == Float.TYPE - || param == Double.TYPE); - } catch (Exception e) { - assertTrue("Byte invalid exception: " + e, - e instanceof IllegalArgumentException); - assertTrue("Byte invalid failure: " + methods[i], - param == Boolean.TYPE || param == Character.TYPE); - } - - try { - methods[i].invoke(testMethod, new Object[] { new Short( - (short) 1) }); - assertTrue("invalid invoke with Short: " + methods[i], - param == Short.TYPE || param == Integer.TYPE - || param == Long.TYPE - || param == Float.TYPE - || param == Double.TYPE); - } catch (Exception e) { - assertTrue("Short invalid exception: " + e, - e instanceof IllegalArgumentException); - assertTrue("Short invalid failure: " + methods[i], - param == Byte.TYPE || param == Boolean.TYPE - || param == Character.TYPE); - } - - try { - methods[i].invoke(testMethod, - new Object[] { new Integer(1) }); - assertTrue("invalid invoke with Integer: " + methods[i], - param == Integer.TYPE || param == Long.TYPE - || param == Float.TYPE - || param == Double.TYPE); - } catch (Exception e) { - assertTrue("Integer invalid exception: " + e, - e instanceof IllegalArgumentException); - assertTrue("Integer invalid failure: " + methods[i], - param == Byte.TYPE || param == Short.TYPE - || param == Boolean.TYPE - || param == Character.TYPE); - } - - try { - methods[i].invoke(testMethod, new Object[] { new Long(1) }); - assertTrue("invalid invoke with Long: " + methods[i], - param == Long.TYPE || param == Float.TYPE - || param == Double.TYPE); - } catch (Exception e) { - assertTrue("Long invalid exception: " + e, - e instanceof IllegalArgumentException); - assertTrue("Long invalid failure: " + methods[i], - param == Byte.TYPE || param == Short.TYPE - || param == Integer.TYPE - || param == Boolean.TYPE - || param == Character.TYPE); - } - - try { - methods[i].invoke(testMethod, new Object[] { new Character( - 'a') }); - assertTrue("invalid invoke with Character: " + methods[i], - param == Character.TYPE || param == Integer.TYPE - || param == Long.TYPE - || param == Float.TYPE - || param == Double.TYPE); - } catch (Exception e) { - assertTrue("Character invalid exception: " + e, - e instanceof IllegalArgumentException); - assertTrue("Character invalid failure: " + methods[i], - param == Byte.TYPE || param == Short.TYPE - || param == Boolean.TYPE); - } - - try { - methods[i] - .invoke(testMethod, new Object[] { new Float(1) }); - assertTrue("invalid invoke with Float: " + methods[i], - param == Float.TYPE || param == Double.TYPE); - } catch (Exception e) { - assertTrue("Float invalid exception: " + e, - e instanceof IllegalArgumentException); - assertTrue("Float invalid failure: " + methods[i], - param == Byte.TYPE || param == Short.TYPE - || param == Integer.TYPE - || param == Long.TYPE - || param == Boolean.TYPE - || param == Character.TYPE); - } - - try { - methods[i].invoke(testMethod, - new Object[] { new Double(1) }); - assertTrue("invalid invoke with Double: " + methods[i], - param == Double.TYPE); - } catch (Exception e) { - assertTrue("Double invalid exception: " + e, - e instanceof IllegalArgumentException); - assertTrue("Double invalid failure: " + methods[i], - param == Byte.TYPE || param == Short.TYPE - || param == Integer.TYPE - || param == Long.TYPE - || param == Boolean.TYPE - || param == Character.TYPE - || param == Float.TYPE); - } - - try { - methods[i].invoke(testMethod, new Object[] { new Boolean( - true) }); - assertTrue("invalid invoke with Boolean: " + methods[i], - param == Boolean.TYPE); - } catch (Exception e) { - assertTrue("Boolean invalid exception: " + e, - e instanceof IllegalArgumentException); - assertTrue("Boolean invalid failure: " + methods[i], - param == Byte.TYPE || param == Short.TYPE - || param == Integer.TYPE - || param == Long.TYPE - || param == Character.TYPE - || param == Float.TYPE - || param == Double.TYPE); - } - } - } - } - - /** - * java.lang.reflect.Method#toString() - */ - public void test_toString() { - // Test for method java.lang.String java.lang.reflect.Method.toString() - Method mth = null; - Class[] parms = { int.class, short.class, String.class, boolean.class, - Object.class, long.class, byte.class, char.class, double.class, - float.class }; - try { - - mth = TestMethod.class.getDeclaredMethod("printTest", parms); - } catch (Exception e) { - fail("Exception during toString test : " + e.getMessage()); - } - - assertTrue( - "Returned incorrect string for method: " + mth.toString(), - mth - .toString() - .equals( - "public static final void tests.api.java.lang.reflect.MethodTest$TestMethod.printTest(int,short,java.lang.String,boolean,java.lang.Object,long,byte,char,double,float)")); - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/lang/reflect/ParameterizedTypeTest.java b/luni/src/test/java/tests/api/java/lang/reflect/ParameterizedTypeTest.java deleted file mode 100644 index fcb9042..0000000 --- a/luni/src/test/java/tests/api/java/lang/reflect/ParameterizedTypeTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2008 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 tests.api.java.lang.reflect; - -import java.lang.reflect.Field; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; - -/** - * Tests parameterized types and their properties. - */ -public class ParameterizedTypeTest extends GenericReflectionTestsBase { - - static class A<T>{} - static class B extends A<String>{} - - public void testStringParameterizedSuperClass() { - Class<? extends B> clazz = B.class; - Type genericSuperclass = clazz.getGenericSuperclass(); - assertInstanceOf(ParameterizedType.class, genericSuperclass); - ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass; - assertEquals(ParameterizedTypeTest.class, parameterizedType.getOwnerType()); - assertEquals(A.class, parameterizedType.getRawType()); - - Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); - assertLenghtOne(actualTypeArguments); - assertEquals(String.class, actualTypeArguments[0]); - } - - static class C<T>{} - static class D<T> extends C<T>{} - - public void testTypeParameterizedSuperClass() { - Class<? extends D> clazz = D.class; - Type genericSuperclass = clazz.getGenericSuperclass(); - assertInstanceOf(ParameterizedType.class, genericSuperclass); - ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass; - assertEquals(ParameterizedTypeTest.class, parameterizedType.getOwnerType()); - assertEquals(C.class, parameterizedType.getRawType()); - - Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); - assertLenghtOne(actualTypeArguments); - assertEquals(getTypeParameter(D.class), actualTypeArguments[0]); - } - - static class E<T>{} - static class F<T>{ - E<T> e; - } - - public void testParameterizedMemeber() throws Exception{ - Class<? extends F> clazz = F.class; - Field field = clazz.getDeclaredField("e"); - assertInstanceOf(ParameterizedType.class, field.getGenericType()); - ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); - assertEquals(ParameterizedTypeTest.class, parameterizedType.getOwnerType()); - assertEquals(E.class, parameterizedType.getRawType()); - - Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); - assertLenghtOne(actualTypeArguments); - assertEquals(getTypeParameter(clazz), actualTypeArguments[0]); - } -} diff --git a/luni/src/test/java/tests/api/java/lang/reflect/ProxyTest.java b/luni/src/test/java/tests/api/java/lang/reflect/ProxyTest.java deleted file mode 100644 index dd496b1..0000000 --- a/luni/src/test/java/tests/api/java/lang/reflect/ProxyTest.java +++ /dev/null @@ -1,319 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.lang.reflect; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.lang.reflect.UndeclaredThrowableException; - -import tests.support.Support_Proxy_I1; -import tests.support.Support_Proxy_I2; -import tests.support.Support_Proxy_ParentException; -import tests.support.Support_Proxy_SubException; - -public class ProxyTest extends junit.framework.TestCase { - - /* - * When multiple interfaces define the same method, the list of thrown - * exceptions are those which can be mapped to another exception in the - * other method: - * - * String foo(String s) throws SubException, LinkageError; - * - * UndeclaredThrowableException wrappers any checked exception which is not - * in the merged list. So ParentException would be wrapped, BUT LinkageError - * would not be since its not an Error/RuntimeException. - * - * interface I1 { String foo(String s) throws ParentException, LinkageError; } - * interface I2 { String foo(String s) throws SubException, Error; } - */ - - interface Broken1 { - public float method(float _number0, float _number1); - } - - class Broken1Invoke implements InvocationHandler { - public Object invoke(Object proxy, Method method, Object[] args) - throws Throwable { - return args[1]; - } - } - - class ProxyCoonstructorTest extends Proxy { - protected ProxyCoonstructorTest(InvocationHandler h) { - super(h); - } - } - - /** - * java.lang.reflect.Proxy#getProxyClass(java.lang.ClassLoader, - * java.lang.Class[]) - */ - public void test_getProxyClassLjava_lang_ClassLoader$Ljava_lang_Class() { - Class proxy = Proxy.getProxyClass(Support_Proxy_I1.class - .getClassLoader(), new Class[] { Support_Proxy_I1.class }); - - assertTrue("Did not create a Proxy subclass ", - proxy.getSuperclass() == Proxy.class); - assertTrue("Does not believe its a Proxy class ", Proxy - .isProxyClass(proxy)); - - assertTrue("Does not believe it's a Proxy class ", Proxy - .isProxyClass(Proxy.getProxyClass(null, - new Class[] { Comparable.class }))); - - try { - Proxy.getProxyClass(Support_Proxy_I1.class.getClassLoader(), - (Class<?>[]) null); - fail("NPE expected"); - } catch (NullPointerException expected) { - } - - try { - Proxy.getProxyClass(Support_Proxy_I1.class.getClassLoader(), - new Class<?>[] {Support_Proxy_I1.class, null}); - fail("NPE expected"); - } catch (NullPointerException expected) { - } - } - - /** - * java.lang.reflect.Proxy#Proxy(java.lang.reflect.InvocationHandler) - */ - public void test_ProxyLjava_lang_reflect_InvocationHandler() { - assertNotNull(new ProxyCoonstructorTest(new InvocationHandler() { - public Object invoke(Object proxy, Method method, Object[] args) - throws Throwable { - return null; - } - })); - } - - - - /** - * java.lang.reflect.Proxy#newProxyInstance(java.lang.ClassLoader, - * java.lang.Class[], java.lang.reflect.InvocationHandler) - */ - public void test_newProxyInstanceLjava_lang_ClassLoader$Ljava_lang_ClassLjava_lang_reflect_InvocationHandler() { - Object p = Proxy.newProxyInstance(Support_Proxy_I1.class - .getClassLoader(), new Class[] { Support_Proxy_I1.class, - Support_Proxy_I2.class }, new InvocationHandler() { - public Object invoke(Object proxy, Method method, Object[] args) - throws Throwable { - if (method.getName().equals("equals")) - return new Boolean(proxy == args[0]); - if (method.getName().equals("array")) - return new int[] { (int) ((long[]) args[0])[1], -1 }; - if (method.getName().equals("string")) { - if ("".equals(args[0])) - throw new Support_Proxy_SubException(); - if ("clone".equals(args[0])) - throw new Support_Proxy_ParentException(); - if ("error".equals(args[0])) - throw new ArrayStoreException(); - if ("any".equals(args[0])) - throw new IllegalAccessException(); - } - return null; - } - }); - - Support_Proxy_I1 proxy = (Support_Proxy_I1) p; - assertTrue("Failed identity test ", proxy.equals(proxy)); - assertTrue("Failed not equals test ", !proxy.equals("")); - int[] result = (int[]) proxy.array(new long[] { 100L, -200L }); - assertEquals("Failed primitive type conversion test ", -200, result[0]); - - boolean worked = false; - try { - proxy.string(""); - } catch (Support_Proxy_SubException e) { - worked = true; - } catch (Support_Proxy_ParentException e) { // is never thrown - } - assertTrue("Problem converting exception ", worked); - - worked = false; - try { - proxy.string("clone"); - } catch (Support_Proxy_ParentException e) { // is never thrown - } catch (UndeclaredThrowableException e) { - worked = true; - } - assertTrue("Problem converting exception ", worked); - - worked = false; - try { - proxy.string("error"); - } catch (Support_Proxy_ParentException e) { // is never thrown - } catch (UndeclaredThrowableException e) { - } catch (RuntimeException e) { - worked = e.getClass() == ArrayStoreException.class; - } - assertTrue("Problem converting exception ", worked); - - worked = false; - try { - proxy.string("any"); - } catch (Support_Proxy_ParentException e) { // is never thrown - } catch (UndeclaredThrowableException e) { - worked = true; - } - assertTrue("Problem converting exception ", worked); - - Broken1 proxyObject = null; - try { - proxyObject = (Broken1) Proxy.newProxyInstance(Broken1.class - .getClassLoader(), new Class[] { Broken1.class }, - new Broken1Invoke()); - } catch (Throwable e) { - fail("Failed to create proxy for class: " + Broken1.class + " - " - + e); - } - float brokenResult = proxyObject.method(2.1f, 5.8f); - assertTrue("Invalid invoke result", brokenResult == 5.8f); - } - - /** - * java.lang.reflect.Proxy#isProxyClass(java.lang.Class) - */ - public void test_isProxyClassLjava_lang_Class() { - Class proxy = Proxy.getProxyClass(Support_Proxy_I1.class - .getClassLoader(), new Class[] { Support_Proxy_I1.class }); - - class Fake extends Proxy { - Fake() { - super(null); - } - } - - Proxy fake = new Proxy(new InvocationHandler() { - public Object invoke(Object proxy, Method method, Object[] args) - throws Throwable { - return null; - } - }) { - }; - - assertTrue("Does not believe its a Proxy class ", Proxy - .isProxyClass(proxy)); - assertTrue("Proxy subclasses do not count ", !Proxy - .isProxyClass(Fake.class)); - assertTrue("Is not a runtime generated Proxy class ", !Proxy - .isProxyClass(fake.getClass())); - boolean thrown = false; - try{ - Proxy.isProxyClass(null); - } catch (NullPointerException ex){ - thrown = true; - } - assertTrue("NPE not thrown.", thrown); - } - - /** - * java.lang.reflect.Proxy#getInvocationHandler(java.lang.Object) - */ - public void test_getInvocationHandlerLjava_lang_Object() { - InvocationHandler handler = new InvocationHandler() { - public Object invoke(Object proxy, Method method, Object[] args) - throws Throwable { - return null; - } - }; - - Object p = Proxy.newProxyInstance(Support_Proxy_I1.class - .getClassLoader(), new Class[] { Support_Proxy_I1.class }, - handler); - - assertTrue("Did not return invocation handler ", Proxy - .getInvocationHandler(p) == handler); - boolean aborted = false; - try { - Proxy.getInvocationHandler(""); - } catch (IllegalArgumentException e) { - aborted = true; - } - assertTrue("Did not detect non proxy object ", aborted); - } - - //Regression Test for HARMONY-2355 - public void test_newProxyInstance_withCompatibleReturnTypes() { - Object o = Proxy - .newProxyInstance(this.getClass().getClassLoader(), - new Class[] { ITestReturnObject.class, - ITestReturnString.class }, - new TestProxyHandler(new TestProxyImpl())); - assertNotNull(o); - } - - public void test_newProxyInstance_withNonCompatibleReturnTypes() { - try { - Proxy.newProxyInstance(this.getClass().getClassLoader(), - new Class[] { ITestReturnInteger.class, - ITestReturnString.class }, new TestProxyHandler( - new TestProxyImpl())); - fail("should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - - } - - public static interface ITestReturnObject { - Object f(); - } - - public static interface ITestReturnString { - String f(); - } - - public static interface ITestReturnInteger { - Integer f(); - } - - public static class TestProxyImpl implements ITestReturnObject, - ITestReturnString { - public String f() { - // do nothing - return null; - } - } - - public static class TestProxyHandler implements InvocationHandler { - private Object proxied; - - public TestProxyHandler(Object object) { - proxied = object; - } - - public Object invoke(Object object, Method method, Object[] args) - throws Throwable { - // do nothing - return method.invoke(proxied, args); - } - - } - - protected void setUp() { - } - - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/lang/reflect/TypeVariableTest.java b/luni/src/test/java/tests/api/java/lang/reflect/TypeVariableTest.java deleted file mode 100644 index cc22852..0000000 --- a/luni/src/test/java/tests/api/java/lang/reflect/TypeVariableTest.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (C) 2008 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 tests.api.java.lang.reflect; - -import java.io.Serializable; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; - -/** - * Tests type variables and their properties. - */ -public class TypeVariableTest extends GenericReflectionTestsBase { - - static class A<T>{} - public void testSimpleTypeVariableOnClass(){ - Class<? extends A> clazz = A.class; - TypeVariable[] typeParameters = clazz.getTypeParameters(); - assertLenghtOne(typeParameters); - TypeVariable<Class> typeVariable = typeParameters[0]; - assertEquals(clazz, typeVariable.getGenericDeclaration()); - assertEquals("T", typeVariable.getName()); - Type[] bounds = typeVariable.getBounds(); - assertLenghtOne(bounds); - assertEquals(Object.class, bounds[0]); - } - - static class B{ - <T> void b(){}; - } - public void testSimpleTypeVariableOnMethod() throws Exception{ - Class<? extends B> clazz = B.class; - Method method = clazz.getDeclaredMethod("b"); - TypeVariable<Method>[] typeParameters = method.getTypeParameters(); - assertLenghtOne(typeParameters); - TypeVariable<Method> typeVariable = typeParameters[0]; - assertEquals(method, typeVariable.getGenericDeclaration()); - assertEquals("T", typeVariable.getName()); - Type[] bounds = typeVariable.getBounds(); - assertLenghtOne(bounds); - assertEquals(Object.class, bounds[0]); - } - - static class C { - <T>C(){} - } - public void testSimpleTypeVariableOnConstructor() throws Exception{ - Class<? extends C> clazz = C.class; - Constructor<?> constructor = clazz.getDeclaredConstructor(); - TypeVariable<?>[] typeParameters = constructor.getTypeParameters(); - assertLenghtOne(typeParameters); - TypeVariable<?> typeVariable = typeParameters[0]; - assertEquals(constructor, typeVariable.getGenericDeclaration()); - assertEquals("T", typeVariable.getName()); - Type[] bounds = typeVariable.getBounds(); - assertLenghtOne(bounds); - assertEquals(Object.class, bounds[0]); - } - - static class D<Q,R,S>{} - public void testMultipleTypeVariablesOnClass() throws Exception { - Class<? extends D> clazz = D.class; - TypeVariable<?>[] typeParameters = clazz.getTypeParameters(); - assertEquals(3, typeParameters.length); - assertEquals("Q", typeParameters[0].getName()); - assertEquals(clazz, typeParameters[0].getGenericDeclaration()); - - assertEquals("R", typeParameters[1].getName()); - assertEquals(clazz, typeParameters[1].getGenericDeclaration()); - - assertEquals("S", typeParameters[2].getName()); - assertEquals(clazz, typeParameters[2].getGenericDeclaration()); - - } - - static class E { - <Q,R,S> void e(){} - } - public void testMultipleTypeVariablesOnMethod() throws Exception { - Class<? extends E> clazz = E.class; - Method method = clazz.getDeclaredMethod("e"); - - TypeVariable<?>[] typeParameters = method.getTypeParameters(); - assertEquals(3, typeParameters.length); - assertEquals("Q", typeParameters[0].getName()); - assertEquals(method, typeParameters[0].getGenericDeclaration()); - - assertEquals("R", typeParameters[1].getName()); - assertEquals(method, typeParameters[1].getGenericDeclaration()); - - assertEquals("S", typeParameters[2].getName()); - assertEquals(method, typeParameters[2].getGenericDeclaration()); - } - - static class F { - <Q,R,S> F(){} - } - public void testMultipleTypeVariablesOnConstructor() throws Exception { - Class<? extends F> clazz = F.class; - Constructor<?> constructor = clazz.getDeclaredConstructor(); - - TypeVariable<?>[] typeParameters = constructor.getTypeParameters(); - assertEquals(3, typeParameters.length); - assertEquals("Q", typeParameters[0].getName()); - assertEquals(constructor, typeParameters[0].getGenericDeclaration()); - - assertEquals("R", typeParameters[1].getName()); - assertEquals(constructor, typeParameters[1].getGenericDeclaration()); - - assertEquals("S", typeParameters[2].getName()); - assertEquals(constructor, typeParameters[2].getGenericDeclaration()); - } - - static class G <T extends Number>{} - - public void testSingleBound() throws Exception { - Class<? extends G> clazz = G.class; - TypeVariable[] typeParameters = clazz.getTypeParameters(); - TypeVariable<Class> typeVariable = typeParameters[0]; - Type[] bounds = typeVariable.getBounds(); - assertLenghtOne(bounds); - assertEquals(Number.class, bounds[0]); - } - - static class H <T extends Number & Serializable >{} - public void testMultipleBound() throws Exception { - Class<? extends H> clazz = H.class; - TypeVariable[] typeParameters = clazz.getTypeParameters(); - TypeVariable<Class> typeVariable = typeParameters[0]; - Type[] bounds = typeVariable.getBounds(); - assertEquals(2, bounds.length); - assertEquals(Number.class, bounds[0]); - assertEquals(Serializable.class, bounds[1]); - } -} diff --git a/luni/src/test/java/tests/api/java/lang/reflect/UndeclaredThrowableExceptionTests.java b/luni/src/test/java/tests/api/java/lang/reflect/UndeclaredThrowableExceptionTests.java deleted file mode 100644 index 8fd2ff3..0000000 --- a/luni/src/test/java/tests/api/java/lang/reflect/UndeclaredThrowableExceptionTests.java +++ /dev/null @@ -1,53 +0,0 @@ -package tests.api.java.lang.reflect; - -import junit.framework.TestCase; - -import java.io.EOFException; -import java.lang.reflect.UndeclaredThrowableException; - -public class UndeclaredThrowableExceptionTests extends TestCase { - - private static EOFException throwable = new EOFException(); - private static String msg = "TEST_MSG"; - /** - * java.lang.reflect.UndeclaredThrowableException#getCause() - */ - public void test_getCause() throws Exception { - UndeclaredThrowableException ute = new UndeclaredThrowableException( - throwable); - assertSame("Wrong cause returned", throwable, ute.getCause()); - } - - /** - * java.lang.reflect.UndeclaredThrowableException#getUndeclaredThrowable() - */ - public void test_getUndeclaredThrowable() throws Exception { - UndeclaredThrowableException ute = new UndeclaredThrowableException( - throwable); - assertSame("Wrong undeclared throwable returned", throwable, ute - .getUndeclaredThrowable()); - } - - /** - * java.lang.reflect.UndeclaredThrowableException#UndeclaredThrowableException(java.lang.Throwable) - */ - public void test_Constructor_Throwable() throws Exception { - UndeclaredThrowableException e = new UndeclaredThrowableException( - throwable); - assertEquals("Wrong cause returned", throwable, e.getCause()); - assertEquals("Wrong throwable returned", throwable, e - .getUndeclaredThrowable()); - } - - /** - * java.lang.reflect.UndeclaredThrowableException#UndeclaredThrowableException(java.lang.Throwable, java.lang.String) - */ - public void test_Constructor_Throwable_String() throws Exception { - UndeclaredThrowableException e = new UndeclaredThrowableException( - throwable, msg); - assertEquals("Wrong cause returned", throwable, e.getCause()); - assertEquals("Wrong throwable returned", throwable, e - .getUndeclaredThrowable()); - assertEquals("Wrong message returned", msg, e.getMessage()); - } -} diff --git a/luni/src/test/java/tests/api/java/lang/reflect/WildcardTypeTest.java b/luni/src/test/java/tests/api/java/lang/reflect/WildcardTypeTest.java deleted file mode 100644 index 9f8baeb..0000000 --- a/luni/src/test/java/tests/api/java/lang/reflect/WildcardTypeTest.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (C) 2008 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 tests.api.java.lang.reflect; - - -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.lang.reflect.WildcardType; - -/** - * Tests bounded type parameters declared on methods and bounded wildcards. - */ -public class WildcardTypeTest extends GenericReflectionTestsBase { - @SuppressWarnings({"unchecked", "hiding"}) - static class BoundedWildcardsGenericMethods<T> { - - public <T extends BoundedWildcardsGenericMethods> void lowerBoundedParamNoReturn( BoundedWildcardsGenericMethods<? super T> param) {} - - public <T extends BoundedWildcardsGenericMethods> void upperBoundedParamNoReturn( BoundedWildcardsGenericMethods<? extends T> param) {} - - public <T extends BoundedWildcardsGenericMethods> T lowerBoundedParamReturn(BoundedWildcardsGenericMethods<? super T> param) { return (T) new Object(); } - - public <T extends BoundedWildcardsGenericMethods> T upperBoundedParamReturn(BoundedWildcardsGenericMethods<? extends T> param) { return (T) new Object();} - } - - @SuppressWarnings("unchecked") - private static Class<? extends BoundedWildcardsGenericMethods> clazz = BoundedWildcardsGenericMethods.class; - - /** - * Tests that there are is one Type Parameter on the Class itself. - */ - public void testBoundedGenericMethods() { - assertLenghtOne(clazz.getTypeParameters()); - } - - /** - * Tests whether the type parameter is bounded by BoundedGenericMethods like: - * <T extends BoundedGenericMethods>. - * @param method the declaring method - */ - private void checkBoundedTypeParameter(Method method) { - TypeVariable<Method> typeParameter = getTypeParameter(method); - assertEquals("T", typeParameter.getName()); - assertEquals(method, typeParameter.getGenericDeclaration()); - - Type[] bounds = typeParameter.getBounds(); - assertLenghtOne(bounds); - Type bound = bounds[0]; - assertEquals(BoundedWildcardsGenericMethods.class, bound); - } - - private void checkLowerBoundedParameter(Method method) { - Type genericParameterType = method.getGenericParameterTypes()[0]; - assertInstanceOf(ParameterizedType.class, genericParameterType); - - ParameterizedType parameterizedType = (ParameterizedType) genericParameterType; - - Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); - assertLenghtOne(actualTypeArguments); - assertInstanceOf(WildcardType.class, actualTypeArguments[0]); - - WildcardType wildcardType = (WildcardType) actualTypeArguments[0]; - - Type[] lowerBounds = wildcardType.getLowerBounds(); - assertLenghtOne(lowerBounds); - Type lowerBound = lowerBounds[0]; - assertEquals(getTypeParameter(method), lowerBound); - - Type[] upperBounds = wildcardType.getUpperBounds(); - assertEquals(Object.class, upperBounds[0]); - } - - private void checkUpperBoundedParameter(Method method) { - assertLenghtOne(method.getGenericParameterTypes()); - Type genericParameterType = method.getGenericParameterTypes()[0]; - assertInstanceOf(ParameterizedType.class, genericParameterType); - - ParameterizedType parameterizedType = (ParameterizedType) genericParameterType; - Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); - assertLenghtOne(actualTypeArguments); - assertInstanceOf(WildcardType.class, actualTypeArguments[0]); - - WildcardType wildcardType = (WildcardType) actualTypeArguments[0]; - assertLenghtZero(wildcardType.getLowerBounds()); - - Type[] upperBounds = wildcardType.getUpperBounds(); - assertLenghtOne(upperBounds); - Type upperBound = upperBounds[0]; - assertEquals(getTypeParameter(method), upperBound); - } - - @SuppressWarnings("unchecked") - private void checkReturnType(Method method) { - Type genericReturnType = method.getGenericReturnType(); - assertEquals(getTypeParameter(method), genericReturnType); - assertTrue(genericReturnType instanceof TypeVariable); - - TypeVariable<Method> returnTypeVariable = (TypeVariable<Method>) genericReturnType; - assertEquals(method, returnTypeVariable.getGenericDeclaration()); - - Type[] bounds = returnTypeVariable.getBounds(); - assertLenghtOne(bounds); - Type bound = bounds[0]; - - assertEquals(BoundedWildcardsGenericMethods.class, bound); - } - - public void testUpperBoundedParamNoReturn() throws Exception { - Method method = clazz.getMethod("upperBoundedParamNoReturn", BoundedWildcardsGenericMethods.class); - checkBoundedTypeParameter(method); - checkUpperBoundedParameter(method); - } - - public void testLowerBoundedParamReturn() throws Exception { - Method method = clazz.getMethod("lowerBoundedParamReturn", BoundedWildcardsGenericMethods.class); - checkBoundedTypeParameter(method); - checkLowerBoundedParameter(method); - checkReturnType(method); - } - - public void testUpperBoundedParamReturn() throws Exception { - Method method = clazz.getMethod("upperBoundedParamReturn", BoundedWildcardsGenericMethods.class); - checkBoundedTypeParameter(method); - checkUpperBoundedParameter(method); - checkReturnType(method); - } - - public void testLowerBoundedParamNoReturn() throws Exception { - Method method = clazz.getMethod("lowerBoundedParamNoReturn", BoundedWildcardsGenericMethods.class); - checkBoundedTypeParameter(method); - assertLenghtOne(method.getGenericParameterTypes()); - checkLowerBoundedParameter(method); - } - -} diff --git a/luni/src/test/java/tests/api/java/math/MathContextTest.java b/luni/src/test/java/tests/api/java/math/MathContextTest.java deleted file mode 100644 index 9e04342..0000000 --- a/luni/src/test/java/tests/api/java/math/MathContextTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.math; - -import java.math.BigDecimal; -import java.math.MathContext; -import java.math.RoundingMode; - -public class MathContextTest extends junit.framework.TestCase { - - /** - * java.math.MathContext#MathContext(...) - */ - public void test_MathContextConstruction() { - String a = "-12380945E+61"; - BigDecimal aNumber = new BigDecimal(a); - MathContext mcIntRm6hd = new MathContext(6, RoundingMode.HALF_DOWN); - MathContext mcStr6hd = new MathContext("precision=6 roundingMode=HALF_DOWN"); - MathContext mcInt6 = new MathContext(6); - MathContext mcInt134 = new MathContext(134); - - // getPrecision() - assertEquals("MathContext.getPrecision() returns incorrect value", - 6, mcIntRm6hd.getPrecision() ); - assertEquals("MathContext.getPrecision() returns incorrect value", - 134, mcInt134.getPrecision() ); - - // getRoundingMode() - assertEquals("MathContext.getRoundingMode() returns incorrect value", - RoundingMode.HALF_UP, - mcInt6.getRoundingMode()); - assertEquals("MathContext.getRoundingMode() returns incorrect value", - RoundingMode.HALF_DOWN, mcIntRm6hd.getRoundingMode() ); - - // toString() - assertEquals("MathContext.toString() returning incorrect value", - "precision=6 roundingMode=HALF_DOWN", mcIntRm6hd.toString() ); - assertEquals("MathContext.toString() returning incorrect value", - "precision=6 roundingMode=HALF_UP", mcInt6.toString() ); - - // equals(.) - assertEquals("Equal MathContexts are not equal ", - mcIntRm6hd, mcStr6hd ); - assertFalse("Different MathContexts are reported as equal ", - mcInt6.equals(mcStr6hd) ); - assertFalse("Different MathContexts are reported as equal ", - mcInt6.equals(mcInt134) ); - - // hashCode(.) - assertEquals("Equal MathContexts have different hashcodes ", - mcIntRm6hd.hashCode(), mcStr6hd.hashCode() ); - assertFalse("Different MathContexts have equal hashcodes ", - mcInt6.hashCode() == mcStr6hd.hashCode() ); - assertFalse("Different MathContexts have equal hashcodes ", - mcInt6.hashCode() == mcInt134.hashCode() ); - - // other: - BigDecimal res = aNumber.abs(mcInt6); - assertEquals("MathContext Constructor with int precision failed", - new BigDecimal("1.23809E+68"), - res); - } - -} diff --git a/luni/src/test/java/tests/api/java/math/OldBigIntegerTest.java b/luni/src/test/java/tests/api/java/math/OldBigIntegerTest.java deleted file mode 100644 index 167ebe8..0000000 --- a/luni/src/test/java/tests/api/java/math/OldBigIntegerTest.java +++ /dev/null @@ -1,372 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.math; - -import java.math.BigInteger; -import java.util.Random; - -public class OldBigIntegerTest extends junit.framework.TestCase { - - BigInteger minusOne = new BigInteger("-1", 10); - - BigInteger two = new BigInteger("2", 10); - - BigInteger aZillion = new BigInteger("100000000000000000000000000000000000000000000000000", 10); - - Random rand = new Random(); - - BigInteger bi; - - BigInteger bi2; - - BigInteger bi3; - - /** - * java.math.BigInteger#BigInteger(int, java.util.Random) - */ - public void test_ConstructorILjava_util_Random() { - // regression test for HARMONY-1047 - try { - new BigInteger(128, (Random) null); - fail(); - } catch (NullPointerException expected) { - } - - bi = new BigInteger(70, rand); - bi2 = new BigInteger(70, rand); - assertTrue("Random number is negative", bi.compareTo(BigInteger.ZERO) >= 0); - assertTrue("Random number is too big", bi.compareTo(two.pow(70)) < 0); - assertTrue( - "Two random numbers in a row are the same (might not be a bug but it very likely is)", - !bi.equals(bi2)); - assertTrue("Not zero", new BigInteger(0, rand).equals(BigInteger.ZERO)); - - try { - new BigInteger(-1, (Random)null); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - // PASSED - } - } - - /** - * java.math.BigInteger#BigInteger(int, int, java.util.Random) - */ - // BIGNUM returns no Primes smaller than 16 bits. - public void test_ConstructorIILjava_util_Random() { - BigInteger bi1 = new BigInteger(10, 5, rand); - BigInteger bi2 = new BigInteger(10, 5, rand); - assertTrue(bi1 + " is negative", bi1.compareTo(BigInteger.ZERO) >= 0); - assertTrue(bi1 + " is too big", bi1.compareTo(new BigInteger("1024", 10)) < 0); - assertTrue(bi2 + " is negative", bi2.compareTo(BigInteger.ZERO) >= 0); - assertTrue(bi2 + " is too big", bi2.compareTo(new BigInteger("1024", 10)) < 0); - - Random rand = new Random(); - BigInteger bi; - int certainty[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, - Integer.MIN_VALUE, Integer.MIN_VALUE + 1, -2, -1 }; - for (int i = 2; i <= 20; i++) { - for (int c = 0; c < certainty.length; c++) { - bi = new BigInteger(i, c, rand); // Create BigInteger - assertEquals(i, bi.bitLength()); - } - } - - try { - new BigInteger(1, 80, (Random)null); - fail("ArithmeticException expected"); - } catch (ArithmeticException expected) { - } - - try { - new BigInteger(-1, (Random)null); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - } - } - -// public void test_SpecialPrimes() { -// System.out.println("test_SpecialPrimes"); -// final BigInteger TWO = BigInteger.valueOf(2); -// BigInteger p, q; -// for (;;) { -// p = new BigInteger(1024, 23, new Random()); -// q = p.subtract(BigInteger.ONE).divide(TWO); -// if (q.isProbablePrime(20)) { -// System.out.println(q); -// System.out.println(p); -// break; -// } -// System.out.print("."); -// } -// fail("isProbablePrime failed for: " + bi); -// } - - /** - * java.math.BigInteger#isProbablePrime(int) - */ - public void test_isProbablePrimeI() { - int fails = 0; - bi = new BigInteger(20, 20, rand); - if (!bi.isProbablePrime(17)) { - fails++; - } - bi = new BigInteger("4", 10); - if (bi.isProbablePrime(17)) { - fail("isProbablePrime failed for: " + bi); - } - bi = BigInteger.valueOf(17L * 13L); - if (bi.isProbablePrime(17)) { - fail("isProbablePrime failed for: " + bi); - } - for (long a = 2; a < 1000; a++) { - if (isPrime(a)) { - assertTrue("false negative on prime number <1000", BigInteger - .valueOf(a).isProbablePrime(5)); - } else if (BigInteger.valueOf(a).isProbablePrime(17)) { - System.out.println("isProbablePrime failed for: " + a); - fails++; - } - } - for (int a = 0; a < 1000; a++) { - bi = BigInteger.valueOf(rand.nextInt(1000000)).multiply( - BigInteger.valueOf(rand.nextInt(1000000))); - if (bi.isProbablePrime(17)) { - System.out.println("isProbablePrime failed for: " + bi); - fails++; - } - } - for (int a = 0; a < 200; a++) { - bi = new BigInteger(70, rand).multiply(new BigInteger(70, rand)); - if (bi.isProbablePrime(17)) { - System.out.println("isProbablePrime failed for: " + bi); - fails++; - } - } - assertTrue("Too many false positives - may indicate a problem", - fails <= 1); - - // - // And now some tests on real big integers: - // - bi = new BigInteger("153890972191202256150310830154922163807316525358455215516067727076235016932726922093888770552128767458882963869421440585369743", 10); - if (!bi.isProbablePrime(80)) { - fail("isProbablePrime failed for: " + bi); - } - bi = new BigInteger("2090575416269141767246491983797422123741252476560371649798066134123893524014911825188890458270426076468664046568752890122415061377308817346303546688282957897504000216241497550243010257911214329646877810655164658470278901030511157372440751259674247310396158238588463284702737181653", 10); - if (!bi.isProbablePrime(80)) { - fail("isProbablePrime failed for: " + bi); - } - // - for (int bitLength = 100; bitLength <= 600; bitLength += 100) { - BigInteger a = BigInteger.probablePrime(bitLength, rand); - BigInteger b = BigInteger.probablePrime(bitLength, rand); - BigInteger c = a.multiply(b); - assertFalse("isProbablePrime failed for product of two large primes" + - a + " * " + b + " = " + c + - " (bitLength = " + bitLength + ")", - c.isProbablePrime(80) ); - } - } - - /** - * java.math.BigInteger#nextProbablePrime() - */ - public void test_nextProbablePrime() { - largePrimesProduct( - new BigInteger("2537895984043447429238717358455377929009126353874925049325287329295635198252046158619999217453233889378619619008359011789"), - new BigInteger("1711501451602688337873833423534849678524059393231999670806585630179374689152366029939952735718718709436427337762082614710093"), - "4343612660706993434504106787562106084038357258130862545477481433639575850237346784798851102536616749334772541987502120552264920040629526028540204698334741815536099373917351194423681128374184971846099257056996626343051832131340568120612204287123" - ); - - largePrimesProduct( - new BigInteger("4617974730611208463200675282934641082129817404749925308887287017217158545765190433369842932770197341032031682222405074564586462802072184047198214312142847809259437477387527466762251087500170588962277514858557309036550499896961735701485020851"), - new BigInteger("4313158964405728158057980867015758419530142215799386331265837224051830838583266274443105715022196238165196727467066901495701708590167750818040112544031694506528759169669442493029999154074962566165293254671176670719518898684698255068313216294333"), - "19918059106734861363335842730108905466210762564765297409619920041621379008685530738918145604092111306972524565803236031571858280032420140331838737621152630780261815015157696362550138161774466814661069892975003440654998880587960037013294137372709096788892473385003457361736563927256562678181177287998121131179907762285048659075843995525830945659905573174849006768920618442371027575308854641789533211132313916836205357976988977849024687805212304038260207820679964201211309384057458137851" - ); - } - - static void largePrimesProduct(BigInteger a, BigInteger b, String c) { - BigInteger wp = a.multiply(b); - assertFalse("isProbablePrime failed for product of two large primes" + - a + " * " + b + " = " + c, - wp.isProbablePrime(80) ); - BigInteger wpMinusOne = wp.subtract(BigInteger.ONE); - BigInteger next = wpMinusOne.nextProbablePrime(); -// System.out.println(c); -// System.out.println(next); - assertTrue("nextProbablePrime returns wrong number: " + next + - "instead of expected: " + c, - next.toString().equals(c) ); - } - - /** - * java.math.BigInteger#probablePrime(int, java.util.Random) - */ - public void test_probablePrime() { - for (int bitLength = 50; bitLength <= 1050; bitLength += 100) { - BigInteger a = BigInteger.probablePrime(bitLength, rand); - assertTrue("isProbablePrime(probablePrime()) failed for: " + bi, - a.isProbablePrime(80)); -// System.out.println(a); -// BigInteger prime = a.nextProbablePrime(); -// System.out.print("Next Probable Prime is "); -// System.out.println(prime); - } - } - -// BEGIN android-added -// public void testModPowPerformance() { -// Random rnd = new Random(); -// for (int i = 0; i < 10; i++) { -// BigInteger a = new BigInteger(512, rnd); -// BigInteger m = new BigInteger(1024, rnd); -// BigInteger p = new BigInteger(256, rnd); -// BigInteger mp = a.modPow(p, m); -// System.out.println(mp); -// } -// } - -// shows factor 20 speed up (BIGNUM to Harmony Java): -// public void testNextProbablePrime() { -// Random rnd = new Random(); -// rnd.setSeed(0); -// for (int i = 1; i <= 32; i += 1) { -// BigInteger a = new BigInteger(i, rnd); -// System.out.println(a); -// BigInteger prime = a.nextProbablePrime(); -// System.out.print("Next Probable Prime is "); -// System.out.println(prime); -// } -// for (int i = 1; i <= 32; i += 4) { -// BigInteger a = new BigInteger(32 * i, rnd); -// System.out.println(a); -// BigInteger prime = a.nextProbablePrime(); -// System.out.print("Next Probable Prime is "); -// System.out.println(prime); -// } -// } - -// shows factor 20 speed up (BIGNUM to Harmony Java): -// shows that certainty 80 is "practically aquivalent" to certainty 100 -// public void testPrimeGenPerformance() { -// Random rnd = new Random(); -// rnd.setSeed(0); -// for (int i = 1; i <= 32; i +=8 ) { -// BigInteger a = new BigInteger(32 * i, 80, rnd); -// System.out.println(a); -// System.out.println("Now testing it again:"); -// if (a.isProbablePrime(100)) { -// System.out.println("************************ PASSED! **************************"); -// } else { -// System.out.println("************************ FAILED!!! **************************"); -// System.out.println("************************ FAILED!!! **************************"); -// System.out.println("************************ FAILED!!! **************************"); -// System.out.println("************************ FAILED!!! **************************"); -// System.out.println("************************ FAILED!!! **************************"); -// System.out.println("************************ FAILED!!! **************************"); -// } -// } -// } -// END android-added - - - - /** - * java.math.BigInteger#add(java.math.BigInteger) - */ - public void test_addLjava_math_BigInteger() { - assertTrue("Incorrect sum--wanted a zillion", aZillion.add(aZillion) - .add(aZillion.negate()).equals(aZillion)); - assertTrue("0+0", BigInteger.ZERO.add(BigInteger.ZERO).equals(BigInteger.ZERO)); - assertTrue("0+1", BigInteger.ZERO.add(BigInteger.ONE).equals(BigInteger.ONE)); - assertTrue("1+0", BigInteger.ONE.add(BigInteger.ZERO).equals(BigInteger.ONE)); - assertTrue("1+1", BigInteger.ONE.add(BigInteger.ONE).equals(two)); - assertTrue("0+(-1)", BigInteger.ZERO.add(minusOne).equals(minusOne)); - assertTrue("(-1)+0", minusOne.add(BigInteger.ZERO).equals(minusOne)); - assertTrue("(-1)+(-1)", minusOne.add(minusOne).equals(new BigInteger("-2", 10))); - assertTrue("1+(-1)", BigInteger.ONE.add(minusOne).equals(BigInteger.ZERO)); - assertTrue("(-1)+1", minusOne.add(BigInteger.ONE).equals(BigInteger.ZERO)); - - for (int i = 0; i < 200; i++) { - BigInteger midbit = BigInteger.ZERO.setBit(i); - assertTrue("add fails to carry on bit " + i, midbit.add(midbit) - .equals(BigInteger.ZERO.setBit(i + 1))); - } - BigInteger bi2p3 = bi2.add(bi3); - BigInteger bi3p2 = bi3.add(bi2); - assertTrue("bi2p3=bi3p2", bi2p3.equals(bi3p2)); - - - // BESSER UEBERGREIFENDE TESTS MACHEN IN FORM VON STRESS TEST. - // add large positive + small positive - BigInteger sum = aZillion; - BigInteger increment = BigInteger.ONE; - for (int i = 0; i < 20; i++) { - - } - - // add large positive + small negative - - // add large negative + small positive - - // add large negative + small negative - } - - public void testClone() { - // Regression test for HARMONY-1770 - MyBigInteger myBigInteger = new MyBigInteger("12345"); - myBigInteger = (MyBigInteger) myBigInteger.clone(); - } - - static class MyBigInteger extends BigInteger implements Cloneable { - public MyBigInteger(String val) { - super(val); - } - public Object clone() { - try { - return super.clone(); - } catch (CloneNotSupportedException e) { - throw new AssertionError(e); // android-changed - } - } - } - - @Override - protected void setUp() { - bi2 = new BigInteger("4576829475724387584378543764555", 16); - bi3 = new BigInteger("43987298363278574365732645872643587624387563245", 16); - } - - private boolean isPrime(long b) { - if (b == 2) { - return true; - } - // check for div by 2 - if ((b & 1L) == 0) { - return false; - } - long maxlen = ((long) Math.sqrt(b)) + 2; - for (long x = 3; x < maxlen; x += 2) { - if (b % x == 0) { - return false; - } - } - return true; - } -} diff --git a/luni/src/test/java/tests/api/java/math/RoundingModeTest.java b/luni/src/test/java/tests/api/java/math/RoundingModeTest.java deleted file mode 100644 index 50a77df..0000000 --- a/luni/src/test/java/tests/api/java/math/RoundingModeTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.math; - -import java.math.BigDecimal; -import java.math.RoundingMode; - -public class RoundingModeTest extends junit.framework.TestCase { - - /** - * java.math.RoundingMode#valueOf(int) - */ - public void test_valueOfI() { - assertEquals("valueOf failed for ROUND_CEILING", RoundingMode.valueOf(BigDecimal.ROUND_CEILING), RoundingMode.CEILING); - assertEquals("valueOf failed for ROUND_DOWN", RoundingMode.valueOf(BigDecimal.ROUND_DOWN), RoundingMode.DOWN); - assertEquals("valueOf failed for ROUND_FLOOR", RoundingMode.valueOf(BigDecimal.ROUND_FLOOR), RoundingMode.FLOOR); - assertEquals("valueOf failed for ROUND_HALF_DOWN", RoundingMode.valueOf(BigDecimal.ROUND_HALF_DOWN), RoundingMode.HALF_DOWN); - assertEquals("valueOf failed for ROUND_HALF_EVEN", RoundingMode.valueOf(BigDecimal.ROUND_HALF_EVEN), RoundingMode.HALF_EVEN); - assertEquals("valueOf failed for ROUND_HALF_UP", RoundingMode.valueOf(BigDecimal.ROUND_HALF_UP), RoundingMode.HALF_UP); - assertEquals("valueOf failed for ROUND_UNNECESSARY", RoundingMode.valueOf(BigDecimal.ROUND_UNNECESSARY), RoundingMode.UNNECESSARY); - assertEquals("valueOf failed for ROUND_UP", RoundingMode.valueOf(BigDecimal.ROUND_UP), RoundingMode.UP); - try { - RoundingMode.valueOf(13); - fail("IllegalArgumentException expected for RoundingMode(13)"); - } catch (IllegalArgumentException e) { - } - try { - RoundingMode.valueOf(-1); - fail("IllegalArgumentException expected for RoundingMode(-1)"); - } catch (IllegalArgumentException e) { - } - } - -} diff --git a/luni/src/test/java/tests/api/java/util/AbstractListTest.java b/luni/src/test/java/tests/api/java/util/AbstractListTest.java deleted file mode 100644 index 3cda30f..0000000 --- a/luni/src/test/java/tests/api/java/util/AbstractListTest.java +++ /dev/null @@ -1,293 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.AbstractList; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.ListIterator; -import java.util.RandomAccess; - -public class AbstractListTest extends junit.framework.TestCase { - - static class SimpleList extends AbstractList { - ArrayList arrayList; - - SimpleList() { - this.arrayList = new ArrayList(); - } - - public Object get(int index) { - return this.arrayList.get(index); - } - - public void add(int i, Object o) { - this.arrayList.add(i, o); - } - - public Object remove(int i) { - return this.arrayList.remove(i); - } - - public int size() { - return this.arrayList.size(); - } - } - - /** - * java.util.AbstractList#hashCode() - */ - public void test_hashCode() { - - List list = new ArrayList(); - list.add(new Integer(3)); - list.add(new Integer(15)); - list.add(new Integer(5)); - list.add(new Integer(1)); - list.add(new Integer(7)); - int hashCode = 1; - Iterator i = list.iterator(); - while (i.hasNext()) { - Object obj = i.next(); - hashCode = 31 * hashCode + (obj == null ? 0 : obj.hashCode()); - } - assertTrue("Incorrect hashCode returned. Wanted: " + hashCode - + " got: " + list.hashCode(), hashCode == list.hashCode()); - } - - /** - * java.util.AbstractList#iterator() - */ - public void test_iterator() { - SimpleList list = new SimpleList(); - list.add(new Object()); - list.add(new Object()); - Iterator it = list.iterator(); - it.next(); - it.remove(); - it.next(); - } - - /** - * java.util.AbstractList#listIterator() - */ - public void test_listIterator() { - Integer tempValue; - List list = new ArrayList(); - list.add(new Integer(3)); - list.add(new Integer(15)); - list.add(new Integer(5)); - list.add(new Integer(1)); - list.add(new Integer(7)); - ListIterator lit = list.listIterator(); - assertTrue("Should not have previous", !lit.hasPrevious()); - assertTrue("Should have next", lit.hasNext()); - tempValue = (Integer) lit.next(); - assertTrue("next returned wrong value. Wanted 3, got: " + tempValue, - tempValue.intValue() == 3); - tempValue = (Integer) lit.previous(); - - SimpleList list2 = new SimpleList(); - list2.add(new Object()); - ListIterator lit2 = list2.listIterator(); - lit2.add(new Object()); - lit2.next(); - } - - /** - * java.util.AbstractList#subList(int, int) - */ - public void test_subListII() { - // Test each of the SubList operations to ensure a - // ConcurrentModificationException does not occur on an AbstractList - // which does not update modCount - SimpleList mList = new SimpleList(); - mList.add(new Object()); - mList.add(new Object()); - List sList = mList.subList(0, 2); - sList.add(new Object()); // calls add(int, Object) - sList.get(0); - - sList.add(0, new Object()); - sList.get(0); - - sList.addAll(Arrays.asList(new String[] { "1", "2" })); - sList.get(0); - - sList.addAll(0, Arrays.asList(new String[] { "3", "4" })); - sList.get(0); - - sList.remove(0); - sList.get(0); - - ListIterator lit = sList.listIterator(); - lit.add(new Object()); - lit.next(); - lit.remove(); - lit.next(); - - sList.clear(); // calls removeRange() - sList.add(new Object()); - - // test the type of sublist that is returned - List al = new ArrayList(); - for (int i = 0; i < 10; i++) { - al.add(new Integer(i)); - } - assertTrue( - "Sublist returned should have implemented Random Access interface", - al.subList(3, 7) instanceof RandomAccess); - - List ll = new LinkedList(); - for (int i = 0; i < 10; i++) { - ll.add(new Integer(i)); - } - assertTrue( - "Sublist returned should not have implemented Random Access interface", - !(ll.subList(3, 7) instanceof RandomAccess)); - - } - - /** - * java.util.AbstractList#subList(int, int) - */ - public void test_subList_empty() { - // Regression for HARMONY-389 - List al = new ArrayList(); - al.add("one"); - List emptySubList = al.subList(0, 0); - - try { - emptySubList.get(0); - fail("emptySubList.get(0) should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - // expected - } - - try { - emptySubList.set(0, "one"); - fail("emptySubList.set(0,Object) should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - // expected - } - - try { - emptySubList.remove(0); - fail("emptySubList.remove(0) should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - // expected - } - } - - /** - * java.util.AbstractList#subList(int, int) - */ - public void test_subList_addAll() { - // Regression for HARMONY-390 - List mainList = new ArrayList(); - Object[] mainObjects = { "a", "b", "c" }; - mainList.addAll(Arrays.asList(mainObjects)); - List subList = mainList.subList(1, 2); - assertFalse("subList should not contain \"a\"", subList.contains("a")); - assertFalse("subList should not contain \"c\"", subList.contains("c")); - assertTrue("subList should contain \"b\"", subList.contains("b")); - - Object[] subObjects = { "one", "two", "three" }; - subList.addAll(Arrays.asList(subObjects)); - assertFalse("subList should not contain \"a\"", subList.contains("a")); - assertFalse("subList should not contain \"c\"", subList.contains("c")); - - Object[] expected = { "b", "one", "two", "three" }; - ListIterator iter = subList.listIterator(); - for (int i = 0; i < expected.length; i++) { - assertTrue("subList should contain " + expected[i], subList - .contains(expected[i])); - assertTrue("should be more elements", iter.hasNext()); - assertEquals("element in incorrect position", expected[i], iter - .next()); - } - } - - public void test_indexOfLjava_lang_Object() { - AbstractList al = new ArrayList(); - al.add(0); - al.add(1); - al.add(2); - al.add(3); - al.add(4); - - assertEquals(-1, al.indexOf(5)); - assertEquals(2, al.indexOf(2)); - } - - public void test_lastIndexOfLjava_lang_Object() { - AbstractList al = new ArrayList(); - al.add(0); - al.add(1); - al.add(2); - al.add(2); - al.add(2); - al.add(2); - al.add(2); - al.add(3); - al.add(4); - - assertEquals(-1, al.lastIndexOf(5)); - assertEquals(6, al.lastIndexOf(2)); - } - - public void test_listIteratorI() { - AbstractList al1 = new ArrayList(); - AbstractList al2 = new ArrayList(); - al1.add(0); - al1.add(1); - al1.add(2); - al1.add(3); - al1.add(4); - al2.add(2); - al2.add(3); - al2.add(4); - - Iterator li1 = al1.listIterator(2); - Iterator li2 = al2.listIterator(); - - while(li1.hasNext()&&li2.hasNext()) { - assertEquals(li1.next(), li2.next()); - } - assertSame(li1.hasNext(),li2.hasNext()); - - try { - al1.listIterator(-1); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException ee) { - //expected - } - - try { - al1.listIterator(al1.size() + 1); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException ee) { - //expected - } - } - - protected void doneSuite() {} -} diff --git a/luni/src/test/java/tests/api/java/util/AbstractMapTest.java b/luni/src/test/java/tests/api/java/util/AbstractMapTest.java deleted file mode 100644 index c8f9ce2..0000000 --- a/luni/src/test/java/tests/api/java/util/AbstractMapTest.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.AbstractMap; -import java.util.AbstractSet; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.IdentityHashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; -import java.util.Vector; -import java.util.WeakHashMap; - -public class AbstractMapTest extends junit.framework.TestCase { - - static final String specialKey = "specialKey".intern(); - - static final String specialValue = "specialValue".intern(); - - // The impl of MyMap is not realistic, but serves to create a type - // that uses the default remove behavior. - class MyMap extends AbstractMap { - final Set mySet = new HashSet(1); - - MyMap() { - mySet.add(new Map.Entry() { - public Object getKey() { - return specialKey; - } - - public Object getValue() { - return specialValue; - } - - public Object setValue(Object object) { - return null; - } - }); - } - - public Object put(Object key, Object value) { - return null; - } - - public Set entrySet() { - return mySet; - } - } - - /** - * java.util.AbstractMap#keySet() - */ - public void test_keySet() { - AbstractMap map1 = new HashMap(0); - assertSame("HashMap(0)", map1.keySet(), map1.keySet()); - - AbstractMap map2 = new HashMap(10); - assertSame("HashMap(10)", map2.keySet(), map2.keySet()); - - Map map3 = Collections.EMPTY_MAP; - assertSame("EMPTY_MAP", map3.keySet(), map3.keySet()); - - AbstractMap map4 = new IdentityHashMap(1); - assertSame("IdentityHashMap", map4.keySet(), map4.keySet()); - - AbstractMap map5 = new LinkedHashMap(122); - assertSame("LinkedHashMap", map5.keySet(), map5.keySet()); - - AbstractMap map6 = new TreeMap(); - assertSame("TreeMap", map6.keySet(), map6.keySet()); - - AbstractMap map7 = new WeakHashMap(); - assertSame("WeakHashMap", map7.keySet(), map7.keySet()); - } - - /** - * java.util.AbstractMap#remove(java.lang.Object) - */ - public void test_removeLjava_lang_Object() { - Object key = new Object(); - Object value = new Object(); - - AbstractMap map1 = new HashMap(0); - map1.put("key", value); - assertSame("HashMap(0)", map1.remove("key"), value); - - AbstractMap map4 = new IdentityHashMap(1); - map4.put(key, value); - assertSame("IdentityHashMap", map4.remove(key), value); - - AbstractMap map5 = new LinkedHashMap(122); - map5.put(key, value); - assertSame("LinkedHashMap", map5.remove(key), value); - - AbstractMap map6 = new TreeMap(new Comparator() { - // Bogus comparator - public int compare(Object object1, Object object2) { - return 0; - } - }); - map6.put(key, value); - assertSame("TreeMap", map6.remove(key), value); - - AbstractMap map7 = new WeakHashMap(); - map7.put(key, value); - assertSame("WeakHashMap", map7.remove(key), value); - - AbstractMap aSpecialMap = new MyMap(); - aSpecialMap.put(specialKey, specialValue); - Object valueOut = aSpecialMap.remove(specialKey); - assertSame("MyMap", valueOut, specialValue); - } - - /** - * java.util.AbstractMap#values() - */ - public void test_values() { - AbstractMap map1 = new HashMap(0); - assertSame("HashMap(0)", map1.values(), map1.values()); - - AbstractMap map2 = new HashMap(10); - assertSame("HashMap(10)", map2.values(), map2.values()); - - Map map3 = Collections.EMPTY_MAP; - assertSame("EMPTY_MAP", map3.values(), map3.values()); - - AbstractMap map4 = new IdentityHashMap(1); - assertSame("IdentityHashMap", map4.values(), map4.values()); - - AbstractMap map5 = new LinkedHashMap(122); - assertSame("IdentityHashMap", map5.values(), map5.values()); - - AbstractMap map6 = new TreeMap(); - assertSame("TreeMap", map6.values(), map6.values()); - - AbstractMap map7 = new WeakHashMap(); - assertSame("WeakHashMap", map7.values(), map7.values()); - } - - /** - * java.util.AbstractMap#clone() - */ - public void test_clone() { - class MyMap extends AbstractMap implements Cloneable { - private Map map = new HashMap(); - - public Set entrySet() { - return map.entrySet(); - } - - public Object put(Object key, Object value) { - return map.put(key, value); - } - - public Map getMap() { - return map; - } - - public Object clone() { - try { - return super.clone(); - } catch (CloneNotSupportedException e) { - throw new AssertionError(e); // android-changed - } - } - } - ; - MyMap map = new MyMap(); - map.put("one", "1"); - Map.Entry entry = (Map.Entry) map.entrySet().iterator().next(); - assertTrue("entry not added", entry.getKey() == "one" - && entry.getValue() == "1"); - MyMap mapClone = (MyMap) map.clone(); - assertTrue("clone not shallow", map.getMap() == mapClone.getMap()); - } - - public class AMT extends AbstractMap { - - // Very crude AbstractMap implementation - Vector values = new Vector(); - Vector keys = new Vector(); - - public Set entrySet() { - return new AbstractSet() { - public Iterator iterator() { - return new Iterator() { - int index = 0; - - public boolean hasNext() { - return index < values.size(); - } - - public Object next() { - if (index < values.size()) { - Map.Entry me = new Map.Entry() { - Object v = values.elementAt(index); - - Object k = keys.elementAt(index); - - public Object getKey() { - return k; - } - - public Object getValue() { - return v; - } - - public Object setValue(Object value) { - return null; - } - }; - index++; - return me; - } - return null; - } - - public void remove() { - } - }; - } - - public int size() { - return values.size(); - } - }; - } - - public Object put(Object k, Object v) { - keys.add(k); - values.add(v); - return v; - } - } - - /** - * {@link java.util.AbstractMap#putAll(Map)} - */ - public void test_putAllLMap() { - Hashtable ht = new Hashtable(); - AMT amt = new AMT(); - ht.put("this", "that"); - amt.putAll(ht); - - assertEquals("Should be equal", amt, ht); - } - - public void testEqualsWithNullValues() { - Map<String, String> a = new HashMap<String, String>(); - a.put("a", null); - a.put("b", null); - - Map<String, String> b = new HashMap<String, String>(); - a.put("c", "cat"); - a.put("d", "dog"); - - assertFalse(a.equals(b)); - assertFalse(b.equals(a)); - } - - public void testNullsOnViews() { - Map<String, String> nullHostile = new Hashtable<String, String>(); - - nullHostile.put("a", "apple"); - testNullsOnView(nullHostile.entrySet()); - - nullHostile.put("a", "apple"); - testNullsOnView(nullHostile.keySet()); - - nullHostile.put("a", "apple"); - testNullsOnView(nullHostile.values()); - } - - private void testNullsOnView(Collection<?> view) { - try { - assertFalse(view.contains(null)); - } catch (NullPointerException optional) { - } - - try { - assertFalse(view.remove(null)); - } catch (NullPointerException optional) { - } - - Set<Object> setOfNull = Collections.singleton(null); - assertFalse(view.equals(setOfNull)); - - try { - assertFalse(view.removeAll(setOfNull)); - } catch (NullPointerException optional) { - } - - try { - assertTrue(view.retainAll(setOfNull)); // destructive - } catch (NullPointerException optional) { - } - } - - protected void setUp() { - } - - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/util/AbstractQueueTest.java b/luni/src/test/java/tests/api/java/util/AbstractQueueTest.java deleted file mode 100644 index 5ae490c..0000000 --- a/luni/src/test/java/tests/api/java/util/AbstractQueueTest.java +++ /dev/null @@ -1,323 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.AbstractQueue; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Vector; - -import junit.framework.TestCase; - -public class AbstractQueueTest extends TestCase { - - private MockAbstractQueue<Object> queue; - - private class MockAbstractQueue<E> extends AbstractQueue<E> { - - static final int CAPACITY = 10; - - private int size = 0; - - private Object[] elements = new Object[CAPACITY]; - - public Iterator<E> iterator() { - return new Iterator<E>() { - - private int currentIndex = -1; - - public boolean hasNext() { - return size > 0 && currentIndex < size; - } - - public E next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - currentIndex++; - return (E) elements[currentIndex]; - } - - public void remove() { - if (-1 == currentIndex) { - throw new IllegalStateException(); - } - for (int i = currentIndex; i < size - 1; i++) { - elements[i] = elements[i + 1]; - } - size--; - } - }; - } - - public int size() { - return size; - } - - public boolean offer(E o) { - if (null == o) { - throw new NullPointerException(); - } - - if (size >= CAPACITY) { - return false; - } - - elements[size++] = o; - return true; - } - - public E poll() { - if (isEmpty()) { - return null; - } - E e = (E) elements[0]; - for (int i = 0; i < size - 1; i++) { - elements[i] = elements[i + 1]; - } - size--; - return e; - } - - public E peek() { - if (isEmpty()) { - return null; - } - return (E) elements[0]; - } - - } - - /** - * java.util.AbstractQueue.add(E) - */ - public void test_addLE_null() { - try { - queue.add(null); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - } - - /** - * java.util.AbstractQueue.add(E) - */ - public void test_addLE_Full() { - Object o = new Object(); - - for(int i = 0; i < MockAbstractQueue.CAPACITY; i++ ) { - queue.add(o); - } - - try { - queue.add(o); - fail("should throw IllegalStateException"); - } catch (IllegalStateException e) { - //expected - } - } - - /** - * java.util.AbstractQueue#add(E) - */ - public void test_addLE() { - Object o = new Object(); - final int LAST_INDEX = 4; - for (int i = 0; i < LAST_INDEX; i++) { - queue.add(o); - } - Integer I = new Integer(123456); - queue.add(I); - assertTrue(queue.contains(I)); - Iterator iter = queue.iterator(); - for (int i = 0; i < LAST_INDEX; i++) { - iter.next(); - } - assertTrue(I == iter.next()); - } - - /** - * java.util.AbstractQueue#addAll(E) - */ - public void test_addAllLE_null() { - try { - queue.addAll(null); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - } - - /** - * java.util.AbstractQueue#addAll(E) - */ - public void test_addAllLE_with_null() { - List list = Arrays.asList("MYTESTSTRING", null, new Float(123.456)); - try { - queue.addAll(list); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - } - - /** - * java.util.AbstractQueue#addAll(E) - */ - public void test_addAllLE_full() { - List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); - try { - queue.addAll(list); - fail("should throw IllegalStateException"); - } catch (IllegalStateException e) { - // expected - } - } - - /** - * java.util.AbstractQueue#addAll(E) - */ - public void test_addAllLE_empty() { - // Regression test for HARMONY-1178 - List list = new ArrayList<Object>(0); - assertFalse("Non modification to queue should return false", queue.addAll(list)); - } - - /** - * java.util.AbstractQueue#addAll(E) - */ - public void test_addAllLE_this() { - try { - queue.addAll(queue); - fail("should throw IllegalArgumentException "); - } catch (IllegalArgumentException e) { - // expected - } - } - - public void test_addAllLjava_lang_Object() { - Collection c = new Vector(); - - c.add(0); - c.add(1); - c.add(2); - c.add(3); - c.add(4); - c.add(5); - - assertTrue(queue.addAll(c)); - assertEquals(6, queue.size()); - } - - /** - * java.util.AbstractQueue#clear() - */ - public void test_clear_empty() { - queue.clear(); - assertTrue(queue.isEmpty()); - assertNull(queue.peek()); - } - - /** - * java.util.AbstractQueue#clear() - */ - public void test_clear() { - List list = Arrays.asList(123.456, "MYTESTSTRING", new Object(), 'c'); - queue.addAll(list); - queue.clear(); - assertTrue(queue.isEmpty()); - assertNull(queue.peek()); - } - - /** - * java.util.AbstractQueue#AbstractQueue() - */ - public void test_Constructor() { - MockAbstractQueue queue = new MockAbstractQueue(); - assertNotNull(queue); - } - - /** - * java.util.AbstractQueue#remove() - */ - public void test_remove_null() { - try { - queue.remove(); - fail("should throw NoSuchElementException"); - } catch (NoSuchElementException e) { - // expected - } - - } - - /** - * java.util.AbstractQueue#remove() - */ - public void test_remove() { - char c = 'a'; - queue.add(c); - c = 'b'; - queue.add(c); - assertEquals('a', queue.remove()); - assertEquals('b', queue.remove()); - try { - queue.remove(); - fail("should throw NoSuchElementException"); - } catch (NoSuchElementException e) { - // expected - } - } - - /** - * java.util.AbstractQueue#element() - */ - public void test_element_empty() { - try { - queue.element(); - fail("should throw NoSuchElementException"); - } catch (NoSuchElementException e) { - // expected - } - } - - /** - * java.util.AbstractQueue#element() - */ - public void test_element() { - String s = "MYTESTSTRING_ONE"; - queue.add(s); - s = "MYTESTSTRING_TWO"; - queue.add(s); - assertEquals("MYTESTSTRING_ONE", queue.element()); - // still the first element - assertEquals("MYTESTSTRING_ONE", queue.element()); - } - - protected void setUp() throws Exception { - super.setUp(); - queue = new MockAbstractQueue<Object>(); - } - - protected void tearDown() throws Exception { - super.tearDown(); - queue = null; - } -} diff --git a/luni/src/test/java/tests/api/java/util/AbstractSequentialListTest.java b/luni/src/test/java/tests/api/java/util/AbstractSequentialListTest.java deleted file mode 100644 index 2068f1b..0000000 --- a/luni/src/test/java/tests/api/java/util/AbstractSequentialListTest.java +++ /dev/null @@ -1,603 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.AbstractSequentialList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.ListIterator; -import java.util.Vector; - -import junit.framework.TestCase; - -public class AbstractSequentialListTest extends TestCase { - - @Override - protected void setUp() throws Exception { - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } - - class ASLT<E> extends AbstractSequentialList<E> { - - LinkedList<E> l = new LinkedList<E>(); - - @Override - public ListIterator<E> listIterator(int index) { - return l.listIterator(index); - } - - @Override - public int size() { - return l.size(); - } - } - - /** - * {@link java.util.AbstractSequentialList#addAll(int, java.util.Collection)} - */ - public void test_addAll_ILCollection() { - AbstractSequentialList<String> al = new ASLT<String>(); - String[] someList = { "Aardvark" , - "Bear" , - "Chimpanzee", - "Duck" }; - Collection<String> c = Arrays.asList(someList); - al.addAll(c); - assertTrue("Should return true", al.addAll(2, c)); - } - - class Mock_unsupportedListIterator implements ListIterator { - public void add(Object o) { - throw new UnsupportedOperationException(); - } - - public boolean hasNext() { - return true; - } - - public boolean hasPrevious() { - return false; - } - - public Object next() { - return null; - } - - public int nextIndex() { - return 0; - } - - public Object previous() { - return null; - } - - public int previousIndex() { - return 0; - } - - public void remove() { - } - - public void set(Object o) { - throw new UnsupportedOperationException(); - } - } - - class Mock_ListIterator<E> implements ListIterator<E> { - final String wrongElement = "String"; - public void add(E o) { - if (o.equals(wrongElement)) throw new IllegalArgumentException(); - if (o == null) throw new NullPointerException(); - } - - public boolean hasNext() { - return false; - } - - public boolean hasPrevious() { - return false; - } - - public E next() { - return null; - } - - public int nextIndex() { - return 0; - } - - public E previous() { - return null; - } - - public int previousIndex() { - return 0; - } - - public void remove() { - } - - public void set(E o) { - } - } - - public void test_addAllILjava_util_Collection() { - AbstractSequentialList asl = new AbstractSequentialList() { - - @Override - public int size() { - return 0; - } - - @Override - public ListIterator listIterator(int index) { - return new Mock_unsupportedListIterator(); - } - }; - Collection strV = new Vector<String>(); - - strV.add("String"); - strV.add("1"); - strV.add("3.14"); - - try { - asl.addAll(0, strV); - fail("UnsupportedOperationException expected."); - } catch (UnsupportedOperationException ee) { - //expected - } - try { - asl.addAll(0, null); - fail("NullPointerException expected"); - } catch (NullPointerException ee) { - //expected - } - - //ClassCastException can not be checked for this method. - - asl = new AbstractSequentialList() { - - @Override - public int size() { - return 0; - } - - @Override - public ListIterator listIterator(int index) { - return new Mock_ListIterator(); - } - }; - - try { - asl.addAll(0, strV); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - strV.remove("String"); - strV.add(null); - - try { - asl.addAll(0, strV); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - - strV.remove(null); - asl.addAll(0, strV); - - asl = new LinkedList(); - - try { - asl.addAll(-10, strV); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - //expected - } - - try { - asl.addAll(1, strV); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - //expected - } - } - - public void test_addILjava_lang_Object() { - AbstractSequentialList asl = new AbstractSequentialList() { - - @Override - public int size() { - return 0; - } - - @Override - public ListIterator listIterator(int index) { - return new Mock_unsupportedListIterator(); - } - }; - - try { - asl.add(0, 1); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException e) { - //expected - } - - asl = new AbstractSequentialList() { - - @Override - public int size() { - return 0; - } - - @Override - public ListIterator listIterator(int index) { - return new Mock_ListIterator(); - } - }; - - try { - asl.add(0, "String"); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException ee) { - //expected - } - - try { - asl.add(0, null); - fail("NullPointerException expected"); - } catch (NullPointerException ee) { - //expected - } - - //ClassCastException can not be checked for this method. - - asl.add(0, 1); - - asl = new LinkedList(); - - try { - asl.add(-1, 1); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException ee) { - //expected - } - - asl.add(0, 1); - - try { - asl.add(2, 1); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException ee) { - //expected - } - } - - public void test_getI() { - final String buff[] = {"0", "1", "2", "3", "4", "5"}; - AbstractSequentialList asl = new AbstractSequentialList() { - int currPos = 0; - - @Override - public int size() { - return buff.length; - } - - @Override - public ListIterator listIterator(int index) { - currPos = index; - return new ListIterator() { - public void add(Object o) { - } - - public boolean hasNext() { - return true; - } - - public boolean hasPrevious() { - return false; - } - - public Object next() { - return buff[currPos]; - } - - public int nextIndex() { - return 0; - } - - public Object previous() { - return null; - } - - public int previousIndex() { - return 0; - } - - public void remove() { - } - - public void set(Object o) { - } - }; - } - }; - - for (int i = 0; i < buff.length; i++) { - assertEquals(buff[i], asl.get(i)); - } - - try { - asl.get(asl.size() + 1); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - //expected - } - - try { - asl.get(-1); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - //expected - } - } - - public void test_iterrator() { - AbstractSequentialList asl = new AbstractSequentialList() { - - @Override - public int size() { - return 0; - } - - @Override - public ListIterator listIterator(int index) { - return new Mock_unsupportedListIterator(); - } - }; - - assertTrue(asl.iterator().getClass().toString().contains("Mock_unsupportedListIterator")); - - asl = new AbstractSequentialList() { - - @Override - public int size() { - return 0; - } - - @Override - public ListIterator listIterator(int index) { - return new Mock_ListIterator(); - } - }; - - assertTrue(asl.iterator().getClass().toString().contains("Mock_ListIterator")); - - asl = new AbstractSequentialList() { - - @Override - public int size() { - return 0; - } - - @Override - public ListIterator listIterator(int index) { - return null; - } - }; - assertNull(asl.iterator()); - } - - public void test_removeI() { - AbstractSequentialList asl = new AbstractSequentialList() { - String buff[] = {"0", "1", "2", "3", "4", "5"}; - int currPos = 0; - - @Override - public int size() { - return buff.length; - } - - @Override - public ListIterator listIterator(int index) { - currPos = index; - return new ListIterator() { - public void add(Object o) { - } - - public boolean hasNext() { - return true; - } - - public boolean hasPrevious() { - return false; - } - - public Object next() { - return buff[currPos]; - } - - public int nextIndex() { - return 0; - } - - public Object previous() { - return null; - } - - public int previousIndex() { - return 0; - } - - public void remove() { - buff[currPos] = "removed element"; - } - - public void set(Object o) { - } - }; - } - }; - - try { - asl.remove(asl.size() + 1); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - //expected - } - - try { - asl.remove(-1); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - //expected - } - - for(int i = 0; i < asl.size(); i++) { - assertFalse(asl.get(i).toString().contains("removed element")); - asl.remove(i); - assertTrue(asl.get(i).toString().contains("removed element")); - } - } - - public void test_setILjava_lang_Object() { - AbstractSequentialList asl = new AbstractSequentialList() { - String buff[] = {"0", "1", "2", "3", "4", "5"}; - final String illegalStr = "Illegal element"; - int currPos = 0; - - @Override - public int size() { - return buff.length; - } - - @Override - public ListIterator listIterator(int index) { - currPos = index; - return new ListIterator() { - public void add(Object o) { - } - - public boolean hasNext() { - return true; - } - - public boolean hasPrevious() { - return false; - } - - public Object next() { - return buff[currPos]; - } - - public int nextIndex() { - return 0; - } - - public Object previous() { - return null; - } - - public int previousIndex() { - return 0; - } - - public void remove() { - buff[currPos] = "removed element"; - } - - public void set(Object o) { - if (o == null) throw new NullPointerException(); - if (o.equals(illegalStr)) throw new IllegalArgumentException(); - buff[currPos] = (String) o; - } - }; - } - }; - - try { - asl.set(asl.size() + 1, "new element"); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - //expected - } - - try { - asl.set(-1, "new element"); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - //expected - } - - for(int i = 0; i < asl.size(); i++) { - assertFalse(asl.get(i).toString().contains("new element")); - asl.set(i, "new element"); - assertTrue(asl.get(i).toString().contains("new element")); - } - - try { - asl.set(1, new Double(1)); - fail("ClassCastException expected"); - } catch (ClassCastException e) { - // - } - - try { - asl.set(1, "Illegal element"); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException ee) { - //expected - } - - try { - asl.set(1, null); - fail("NullPointerException expected"); - } catch (NullPointerException ee) { - //expected - } - - asl = new AbstractSequentialList() { - - @Override - public int size() { - return 0; - } - - @Override - public ListIterator listIterator(int index) { - return new Mock_unsupportedListIterator(); - } - }; - - try { - asl.set(0, "New element"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException e) { - //expected - } - } -} diff --git a/luni/src/test/java/tests/api/java/util/ArrayListTest.java b/luni/src/test/java/tests/api/java/util/ArrayListTest.java deleted file mode 100644 index 50d9aa3..0000000 --- a/luni/src/test/java/tests/api/java/util/ArrayListTest.java +++ /dev/null @@ -1,699 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.ConcurrentModificationException; -import java.util.Vector; - -import tests.support.Support_ListTest; - -public class ArrayListTest extends junit.framework.TestCase { - - List alist; - - Object[] objArray; - - /** - * java.util.ArrayList#ArrayList() - */ - public void test_Constructor() { - // Test for method java.util.ArrayList() - new Support_ListTest("", alist).runTest(); - - ArrayList subList = new ArrayList(); - for (int i = -50; i < 150; i++) - subList.add(new Integer(i)); - new Support_ListTest("", subList.subList(50, 150)).runTest(); - } - - /** - * java.util.ArrayList#ArrayList(int) - */ - public void test_ConstructorI() { - // Test for method java.util.ArrayList(int) - ArrayList al = new ArrayList(5); - assertEquals("Incorrect arrayList created", 0, al.size()); - - try { - new ArrayList(-10); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - } - - /** - * java.util.ArrayList#ArrayList(java.util.Collection) - */ - public void test_ConstructorLjava_util_Collection() { - // Test for method java.util.ArrayList(java.util.Collection) - ArrayList al = new ArrayList(Arrays.asList(objArray)); - assertTrue("arrayList created from collection has incorrect size", al - .size() == objArray.length); - for (int counter = 0; counter < objArray.length; counter++) - assertTrue( - "arrayList created from collection has incorrect elements", - al.get(counter) == objArray[counter]); - try { - new ArrayList(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - - } - - /** - * java.util.ArrayList#add(int, java.lang.Object) - */ - public void test_addILjava_lang_Object() { - // Test for method void java.util.ArrayList.add(int, java.lang.Object) - Object o; - alist.add(50, o = new Object()); - assertTrue("Failed to add Object", alist.get(50) == o); - assertTrue("Failed to fix up list after insert", - alist.get(51) == objArray[50] - && (alist.get(52) == objArray[51])); - Object oldItem = alist.get(25); - alist.add(25, null); - assertNull("Should have returned null", alist.get(25)); - assertTrue("Should have returned the old item from slot 25", alist - .get(26) == oldItem); - - try { - alist.add(-1, null); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - //expected - } - - try { - alist.add(alist.size() + 1, null); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - //expected - } - } - - /** - * java.util.ArrayList#add(java.lang.Object) - */ - public void test_addLjava_lang_Object() { - // Test for method boolean java.util.ArrayList.add(java.lang.Object) - Object o = new Object(); - alist.add(o); - assertTrue("Failed to add Object", alist.get(alist.size() - 1) == o); - alist.add(null); - assertNull("Failed to add null", alist.get(alist.size() - 1)); - } - - /** - * java.util.ArrayList#addAll(int, java.util.Collection) - */ - public void test_addAllILjava_util_Collection() { - // Test for method boolean java.util.ArrayList.addAll(int, - // java.util.Collection) - alist.addAll(50, alist); - assertEquals("Returned incorrect size after adding to existing list", - 200, alist.size()); - for (int i = 0; i < 50; i++) - assertTrue("Manipulated elements < index", - alist.get(i) == objArray[i]); - for (int i = 0; i >= 50 && (i < 150); i++) - assertTrue("Failed to ad elements properly", - alist.get(i) == objArray[i - 50]); - for (int i = 0; i >= 150 && (i < 200); i++) - assertTrue("Failed to ad elements properly", - alist.get(i) == objArray[i - 100]); - ArrayList listWithNulls = new ArrayList(); - listWithNulls.add(null); - listWithNulls.add(null); - listWithNulls.add("yoink"); - listWithNulls.add("kazoo"); - listWithNulls.add(null); - alist.addAll(100, listWithNulls); - assertTrue("Incorrect size: " + alist.size(), alist.size() == 205); - assertNull("Item at slot 100 should be null", alist.get(100)); - assertNull("Item at slot 101 should be null", alist.get(101)); - assertEquals("Item at slot 102 should be 'yoink'", - "yoink", alist.get(102)); - assertEquals("Item at slot 103 should be 'kazoo'", - "kazoo", alist.get(103)); - assertNull("Item at slot 104 should be null", alist.get(104)); - alist.addAll(205, listWithNulls); - assertTrue("Incorrect size2: " + alist.size(), alist.size() == 210); - - try { - alist.addAll(-1, listWithNulls); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - //expected - } - - try { - alist.addAll(alist.size() + 1, listWithNulls); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - //expected - } - - try { - alist.addAll(0, null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - -// BEGIN android-removed -// The spec does not mandate that IndexOutOfBoundsException be thrown in -// preference to NullPointerException when the caller desserves both. -// -// /** -// * java.util.ArrayList#addAll(int, java.util.Collection) -// */ -// public void test_addAllILjava_util_Collection_2() { -// // Regression for HARMONY-467 -// ArrayList obj = new ArrayList(); -// try { -// obj.addAll((int) -1, (Collection) null); -// fail("IndexOutOfBoundsException expected"); -// } catch (IndexOutOfBoundsException e) { -// } -// } -// END android-removed - - /** - * java.util.ArrayList#addAll(java.util.Collection) - */ - public void test_addAllLjava_util_Collection() { - // Test for method boolean - // java.util.ArrayList.addAll(java.util.Collection) - List l = new ArrayList(); - l.addAll(alist); - for (int i = 0; i < alist.size(); i++) - assertTrue("Failed to add elements properly", l.get(i).equals( - alist.get(i))); - alist.addAll(alist); - assertEquals("Returned incorrect size after adding to existing list", - 200, alist.size()); - for (int i = 0; i < 100; i++) { - assertTrue("Added to list in incorrect order", alist.get(i) - .equals(l.get(i))); - assertTrue("Failed to add to existing list", alist.get(i + 100) - .equals(l.get(i))); - } - Set setWithNulls = new HashSet(); - setWithNulls.add(null); - setWithNulls.add(null); - setWithNulls.add("yoink"); - setWithNulls.add("kazoo"); - setWithNulls.add(null); - alist.addAll(100, setWithNulls); - Iterator i = setWithNulls.iterator(); - assertTrue("Item at slot 100 is wrong: " + alist.get(100), alist - .get(100) == i.next()); - assertTrue("Item at slot 101 is wrong: " + alist.get(101), alist - .get(101) == i.next()); - assertTrue("Item at slot 103 is wrong: " + alist.get(102), alist - .get(102) == i.next()); - - - // Regression test for Harmony-3481 - ArrayList<Integer> originalList = new ArrayList<Integer>(12); - for (int j = 0; j < 12; j++) { - originalList.add(j); - } - - originalList.remove(0); - originalList.remove(0); - - ArrayList<Integer> additionalList = new ArrayList<Integer>(11); - for (int j = 0; j < 11; j++) { - additionalList.add(j); - } - assertTrue(originalList.addAll(additionalList)); - assertEquals(21, originalList.size()); - - try { - alist.addAll(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.ArrayList#clear() - */ - public void test_clear() { - // Test for method void java.util.ArrayList.clear() - alist.clear(); - assertEquals("List did not clear", 0, alist.size()); - alist.add(null); - alist.add(null); - alist.add(null); - alist.add("bam"); - alist.clear(); - assertEquals("List with nulls did not clear", 0, alist.size()); - /* - * for (int i = 0; i < alist.size(); i++) assertNull("Failed to clear - * list", alist.get(i)); - */ - - } - - /** - * java.util.ArrayList#clone() - */ - public void test_clone() { - // Test for method java.lang.Object java.util.ArrayList.clone() - ArrayList x = (ArrayList) (((ArrayList) (alist)).clone()); - assertTrue("Cloned list was inequal to original", x.equals(alist)); - for (int i = 0; i < alist.size(); i++) - assertTrue("Cloned list contains incorrect elements", - alist.get(i) == x.get(i)); - - alist.add(null); - alist.add(25, null); - x = (ArrayList) (((ArrayList) (alist)).clone()); - assertTrue("nulls test - Cloned list was inequal to original", x - .equals(alist)); - for (int i = 0; i < alist.size(); i++) - assertTrue("nulls test - Cloned list contains incorrect elements", - alist.get(i) == x.get(i)); - - } - - /** - * java.util.ArrayList#contains(java.lang.Object) - */ - public void test_containsLjava_lang_Object() { - // Test for method boolean - // java.util.ArrayList.contains(java.lang.Object) - assertTrue("Returned false for valid element", alist - .contains(objArray[99])); - assertTrue("Returned false for equal element", alist - .contains(new Integer(8))); - assertTrue("Returned true for invalid element", !alist - .contains(new Object())); - assertTrue("Returned true for null but should have returned false", - !alist.contains(null)); - alist.add(null); - assertTrue("Returned false for null but should have returned true", - alist.contains(null)); - } - - /** - * java.util.ArrayList#ensureCapacity(int) - */ - public void test_ensureCapacityI() { - // Test for method void java.util.ArrayList.ensureCapacity(int) - // TODO : There is no good way to test this as it only really impacts on - // the private implementation. - - Object testObject = new Object(); - int capacity = 20; - ArrayList al = new ArrayList(capacity); - int i; - for (i = 0; i < capacity / 2; i++) { - al.add(i, new Object()); - } - al.add(i, testObject); - int location = al.indexOf(testObject); - try { - al.ensureCapacity(capacity); - assertTrue("EnsureCapacity moved objects around in array1.", - location == al.indexOf(testObject)); - al.remove(0); - al.ensureCapacity(capacity); - assertTrue("EnsureCapacity moved objects around in array2.", - --location == al.indexOf(testObject)); - al.ensureCapacity(capacity + 2); - assertTrue("EnsureCapacity did not change location.", - location == al.indexOf(testObject)); - } catch (Exception e) { - fail("Exception during test : " + e.getMessage()); - } - } - - /** - * java.util.ArrayList#get(int) - */ - public void test_getI() { - // Test for method java.lang.Object java.util.ArrayList.get(int) - assertTrue("Returned incorrect element", alist.get(22) == objArray[22]); - try { - alist.get(8765); - fail("Failed to throw expected exception for index > size"); - } catch (IndexOutOfBoundsException e) { - } - } - - /** - * java.util.ArrayList#indexOf(java.lang.Object) - */ - public void test_indexOfLjava_lang_Object() { - // Test for method int java.util.ArrayList.indexOf(java.lang.Object) - assertEquals("Returned incorrect index", - 87, alist.indexOf(objArray[87])); - assertEquals("Returned index for invalid Object", -1, alist - .indexOf(new Object())); - alist.add(25, null); - alist.add(50, null); - assertTrue("Wrong indexOf for null. Wanted 25 got: " - + alist.indexOf(null), alist.indexOf(null) == 25); - } - - /** - * java.util.ArrayList#isEmpty() - */ - public void test_isEmpty() { - // Test for method boolean java.util.ArrayList.isEmpty() - assertTrue("isEmpty returned false for new list", new ArrayList() - .isEmpty()); - assertTrue("Returned true for existing list with elements", !alist - .isEmpty()); - } - - /** - * java.util.ArrayList#lastIndexOf(java.lang.Object) - */ - public void test_lastIndexOfLjava_lang_Object() { - // Test for method int java.util.ArrayList.lastIndexOf(java.lang.Object) - alist.add(new Integer(99)); - assertEquals("Returned incorrect index", - 100, alist.lastIndexOf(objArray[99])); - assertEquals("Returned index for invalid Object", -1, alist - .lastIndexOf(new Object())); - alist.add(25, null); - alist.add(50, null); - assertTrue("Wrong lastIndexOf for null. Wanted 50 got: " - + alist.lastIndexOf(null), alist.lastIndexOf(null) == 50); - } - - /** - * java.util.ArrayList#remove(int) - */ - public void test_removeI() { - // Test for method java.lang.Object java.util.ArrayList.remove(int) - alist.remove(10); - assertEquals("Failed to remove element", - -1, alist.indexOf(objArray[10])); - try { - alist.remove(999); - fail("Failed to throw exception when index out of range"); - } catch (IndexOutOfBoundsException e) { - } - - ArrayList myList = (ArrayList) (((ArrayList) (alist)).clone()); - alist.add(25, null); - alist.add(50, null); - alist.remove(50); - alist.remove(25); - assertTrue("Removing nulls did not work", alist.equals(myList)); - - List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c", - "d", "e", "f", "g" })); - assertTrue("Removed wrong element 1", list.remove(0) == "a"); - assertTrue("Removed wrong element 2", list.remove(4) == "f"); - String[] result = new String[5]; - list.toArray(result); - assertTrue("Removed wrong element 3", Arrays.equals(result, - new String[] { "b", "c", "d", "e", "g" })); - - List l = new ArrayList(0); - l.add(new Object()); - l.add(new Object()); - l.remove(0); - l.remove(0); - try { - l.remove(-1); - fail("-1 should cause exception"); - } catch (IndexOutOfBoundsException e) { - } - try { - l.remove(0); - fail("0 should case exception"); - } catch (IndexOutOfBoundsException e) { - } - } - - /** - * java.util.ArrayList#set(int, java.lang.Object) - */ - public void test_setILjava_lang_Object() { - // Test for method java.lang.Object java.util.ArrayList.set(int, - // java.lang.Object) - Object obj; - alist.set(65, obj = new Object()); - assertTrue("Failed to set object", alist.get(65) == obj); - alist.set(50, null); - assertNull("Setting to null did not work", alist.get(50)); - assertTrue("Setting increased the list's size to: " + alist.size(), - alist.size() == 100); - - try { - alist.set(-1, null); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - //expected - } - - try { - alist.set(alist.size() + 1, null); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - //expected - } - } - - /** - * java.util.ArrayList#size() - */ - public void test_size() { - // Test for method int java.util.ArrayList.size() - assertEquals("Returned incorrect size for exiting list", - 100, alist.size()); - assertEquals("Returned incorrect size for new list", 0, new ArrayList() - .size()); - } - - /** - * java.util.ArrayList#toArray() - */ - public void test_toArray() { - // Test for method java.lang.Object [] java.util.ArrayList.toArray() - alist.set(25, null); - alist.set(75, null); - Object[] obj = alist.toArray(); - assertEquals("Returned array of incorrect size", objArray.length, - obj.length); - - for (int i = 0; i < obj.length; i++) { - if ((i == 25) || (i == 75)) - assertNull("Should be null at: " + i + " but instead got: " - + obj[i], obj[i]); - else - assertTrue("Returned incorrect array: " + i, - obj[i] == objArray[i]); - } - - } - - /** - * java.util.ArrayList#toArray(java.lang.Object[]) - */ - public void test_toArray$Ljava_lang_Object() { - // Test for method java.lang.Object [] - // java.util.ArrayList.toArray(java.lang.Object []) - alist.set(25, null); - alist.set(75, null); - Integer[] argArray = new Integer[100]; - Object[] retArray; - retArray = alist.toArray(argArray); - assertTrue("Returned different array than passed", retArray == argArray); - argArray = new Integer[1000]; - retArray = alist.toArray(argArray); - assertNull("Failed to set first extra element to null", argArray[alist - .size()]); - for (int i = 0; i < 100; i++) { - if ((i == 25) || (i == 75)) - assertNull("Should be null: " + i, retArray[i]); - else - assertTrue("Returned incorrect array: " + i, - retArray[i] == objArray[i]); - } - - String[] strArray = new String[100]; - try { - alist.toArray(strArray); - fail("ArrayStoreException expected"); - } catch (ArrayStoreException e) { - //expected - } - } - - /** - * java.util.ArrayList#trimToSize() - */ - public void test_trimToSize_01() { - // Test for method void java.util.ArrayList.trimToSize() - for (int i = 99; i > 24; i--) - alist.remove(i); - ((ArrayList) alist).trimToSize(); - assertEquals("Returned incorrect size after trim", 25, alist.size()); - for (int i = 0; i < alist.size(); i++) - assertTrue("Trimmed list contained incorrect elements", alist - .get(i) == objArray[i]); - Vector v = new Vector(); - v.add("a"); - v.add("b"); - ArrayList al = new ArrayList(v); - Iterator it = al.iterator(); - al.remove(0); - al.trimToSize(); - try { - it.next(); - fail("should throw a ConcurrentModificationException"); - } catch (ConcurrentModificationException ioobe) { - // expected - } - } - - public void test_trimToSize_02() { - ArrayList list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c", - "d", "e", "f", "g" })); - list.remove("a"); - list.remove("f"); - list.trimToSize(); - } - - /** - * @test java.util.ArrayList#addAll(int, Collection) - */ - public void test_addAll() { - ArrayList list = new ArrayList(); - list.add("one"); - list.add("two"); - assertEquals(2, list.size()); - - list.remove(0); - assertEquals(1, list.size()); - - ArrayList collection = new ArrayList(); - collection.add("1"); - collection.add("2"); - collection.add("3"); - assertEquals(3, collection.size()); - - list.addAll(0, collection); - assertEquals(4, list.size()); - - list.remove(0); - list.remove(0); - assertEquals(2, list.size()); - - collection.add("4"); - collection.add("5"); - collection.add("6"); - collection.add("7"); - collection.add("8"); - collection.add("9"); - collection.add("10"); - collection.add("11"); - collection.add("12"); - - assertEquals(12, collection.size()); - - list.addAll(0, collection); - assertEquals(14, list.size()); - } - - public void test_removeLjava_lang_Object() { - List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c", - "d", "e", "f", "g" })); - assertTrue("Removed wrong element 1", list.remove("a")); - assertTrue("Removed wrong element 2", list.remove("f")); - String[] result = new String[5]; - list.toArray(result); - assertTrue("Removed wrong element 3", Arrays.equals(result, - new String[] { "b", "c", "d", "e", "g" })); - } - - class Mock_ArrayList extends ArrayList { - public Mock_ArrayList() { - } - - public void removeRange(int begin, int end) { - super.removeRange(begin, end); - } - } - - public void test_removeRangeII() { - Mock_ArrayList mal = new Mock_ArrayList(); - mal.add("a"); - mal.add("b"); - mal.add("c"); - mal.add("d"); - mal.add("e"); - mal.add("f"); - mal.add("g"); - mal.add("h"); - - mal.removeRange(2, 4); - - String[] result = new String[6]; - mal.toArray(result); - assertTrue("Removed wrong element 3", Arrays.equals(result, - new String[] { "a", "b", "e", "f", "g", "h"})); - } - - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() throws Exception { - super.setUp(); - - objArray = new Object[100]; - for (int i = 0; i < objArray.length; i++) { - objArray[i] = new Integer(i); - } - - alist = new ArrayList(); - for (int i = 0; i < objArray.length; i++) { - alist.add(objArray[i]); - } - } - - @Override - protected void tearDown() throws Exception { - objArray = null; - alist = null; - - super.tearDown(); - } -} diff --git a/luni/src/test/java/tests/api/java/util/ArraysTest.java b/luni/src/test/java/tests/api/java/util/ArraysTest.java deleted file mode 100644 index 2ca8e70..0000000 --- a/luni/src/test/java/tests/api/java/util/ArraysTest.java +++ /dev/null @@ -1,2403 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.Arrays; -import java.util.Comparator; -import java.util.LinkedList; -import java.util.List; -import java.util.Random; - -import tests.support.Support_UnmodifiableCollectionTest; - -public class ArraysTest extends junit.framework.TestCase { - - public static class ReversedIntegerComparator implements Comparator { - public int compare(Object o1, Object o2) { - return -(((Integer) o1).compareTo((Integer) o2)); - } - - public boolean equals(Object o1, Object o2) { - return ((Integer) o1).compareTo((Integer) o2) == 0; - } - } - - final static int arraySize = 100; - - Object[] objArray; - - boolean[] booleanArray; - - byte[] byteArray; - - char[] charArray; - - double[] doubleArray; - - float[] floatArray; - - int[] intArray; - - long[] longArray; - - Object[] objectArray; - - short[] shortArray; - - /** - * java.util.Arrays#asList(java.lang.Object[]) - */ - public void test_asList$Ljava_lang_Object() { - // Test for method java.util.List - // java.util.Arrays.asList(java.lang.Object []) - List convertedList = Arrays.asList(objectArray); - for (int counter = 0; counter < arraySize; counter++) { - assertTrue( - "Array and List converted from array do not contain identical elements", - convertedList.get(counter) == objectArray[counter]); - } - convertedList.set(50, new Integer(1000)); - assertTrue("set/get did not work on coverted list", convertedList.get( - 50).equals(new Integer(1000))); - convertedList.set(50, new Integer(50)); - new Support_UnmodifiableCollectionTest("", convertedList).runTest(); - - Object[] myArray = (Object[]) (objectArray.clone()); - myArray[30] = null; - myArray[60] = null; - convertedList = Arrays.asList(myArray); - for (int counter = 0; counter < arraySize; counter++) { - assertTrue( - "Array and List converted from array do not contain identical elements", - convertedList.get(counter) == myArray[counter]); - } - - try { - Arrays.asList((Object[])null); - fail("asList with null arg didn't throw NPE"); - } catch (NullPointerException e) { - // Expected - } - } - - /** - * java.util.Arrays#binarySearch(byte[], byte) - */ - public void test_binarySearch$BB() { - // Test for method int java.util.Arrays.binarySearch(byte [], byte) - for (byte counter = 0; counter < arraySize; counter++) - assertTrue("Binary search on byte[] answered incorrect position", - Arrays.binarySearch(byteArray, counter) == counter); - assertEquals("Binary search succeeded for value not present in array 1", - -1, Arrays.binarySearch(intArray, (byte) -1)); - assertTrue( - "Binary search succeeded for value not present in array 2", - Arrays.binarySearch(intArray, (byte) arraySize) == -(arraySize + 1)); - for (byte counter = 0; counter < arraySize; counter++) - byteArray[counter] -= 50; - for (byte counter = 0; counter < arraySize; counter++) - assertTrue( - "Binary search on byte[] involving negative numbers answered incorrect position", - Arrays.binarySearch(byteArray, (byte) (counter - 50)) == counter); - } - - /** - * java.util.Arrays#binarySearch(char[], char) - */ - public void test_binarySearch$CC() { - // Test for method int java.util.Arrays.binarySearch(char [], char) - for (char counter = 0; counter < arraySize; counter++) - assertTrue( - "Binary search on char[] answered incorrect position", - Arrays.binarySearch(charArray, (char) (counter + 1)) == counter); - assertEquals("Binary search succeeded for value not present in array 1", - -1, Arrays.binarySearch(charArray, '\u0000')); - assertTrue( - "Binary search succeeded for value not present in array 2", - Arrays.binarySearch(charArray, (char) (arraySize + 1)) == -(arraySize + 1)); - } - - /** - * java.util.Arrays#binarySearch(double[], double) - */ - public void test_binarySearch$DD() { - // Test for method int java.util.Arrays.binarySearch(double [], double) - for (int counter = 0; counter < arraySize; counter++) - assertTrue( - "Binary search on double[] answered incorrect position", - Arrays.binarySearch(doubleArray, (double) counter) == (double) counter); - assertEquals("Binary search succeeded for value not present in array 1", - -1, Arrays.binarySearch(doubleArray, (double) -1)); - assertTrue( - "Binary search succeeded for value not present in array 2", - Arrays.binarySearch(doubleArray, (double) arraySize) == -(arraySize + 1)); - for (int counter = 0; counter < arraySize; counter++) - doubleArray[counter] -= (double) 50; - for (int counter = 0; counter < arraySize; counter++) - assertTrue( - "Binary search on double[] involving negative numbers answered incorrect position", - Arrays.binarySearch(doubleArray, (double) (counter - 50)) == (double) counter); - - double[] specials = new double[] { Double.NEGATIVE_INFINITY, - -Double.MAX_VALUE, -2d, -Double.MIN_VALUE, -0d, 0d, - Double.MIN_VALUE, 2d, Double.MAX_VALUE, - Double.POSITIVE_INFINITY, Double.NaN }; - for (int i = 0; i < specials.length; i++) { - int result = Arrays.binarySearch(specials, specials[i]); - assertTrue(specials[i] + " invalid: " + result, result == i); - } - assertEquals("-1d", -4, Arrays.binarySearch(specials, -1d)); - assertEquals("1d", -8, Arrays.binarySearch(specials, 1d)); - - } - - /** - * java.util.Arrays#binarySearch(float[], float) - */ - public void test_binarySearch$FF() { - // Test for method int java.util.Arrays.binarySearch(float [], float) - for (int counter = 0; counter < arraySize; counter++) - assertTrue( - "Binary search on float[] answered incorrect position", - Arrays.binarySearch(floatArray, (float) counter) == (float) counter); - assertEquals("Binary search succeeded for value not present in array 1", - -1, Arrays.binarySearch(floatArray, (float) -1)); - assertTrue( - "Binary search succeeded for value not present in array 2", - Arrays.binarySearch(floatArray, (float) arraySize) == -(arraySize + 1)); - for (int counter = 0; counter < arraySize; counter++) - floatArray[counter] -= (float) 50; - for (int counter = 0; counter < arraySize; counter++) - assertTrue( - "Binary search on float[] involving negative numbers answered incorrect position", - Arrays.binarySearch(floatArray, (float) counter - 50) == (float) counter); - - float[] specials = new float[] { Float.NEGATIVE_INFINITY, - -Float.MAX_VALUE, -2f, -Float.MIN_VALUE, -0f, 0f, - Float.MIN_VALUE, 2f, Float.MAX_VALUE, Float.POSITIVE_INFINITY, - Float.NaN }; - for (int i = 0; i < specials.length; i++) { - int result = Arrays.binarySearch(specials, specials[i]); - assertTrue(specials[i] + " invalid: " + result, result == i); - } - assertEquals("-1f", -4, Arrays.binarySearch(specials, -1f)); - assertEquals("1f", -8, Arrays.binarySearch(specials, 1f)); - } - - /** - * java.util.Arrays#binarySearch(int[], int) - */ - public void test_binarySearch$II() { - // Test for method int java.util.Arrays.binarySearch(int [], int) - for (int counter = 0; counter < arraySize; counter++) - assertTrue("Binary search on int[] answered incorrect position", - Arrays.binarySearch(intArray, counter) == counter); - assertEquals("Binary search succeeded for value not present in array 1", - -1, Arrays.binarySearch(intArray, -1)); - assertTrue("Binary search succeeded for value not present in array 2", - Arrays.binarySearch(intArray, arraySize) == -(arraySize + 1)); - for (int counter = 0; counter < arraySize; counter++) - intArray[counter] -= 50; - for (int counter = 0; counter < arraySize; counter++) - assertTrue( - "Binary search on int[] involving negative numbers answered incorrect position", - Arrays.binarySearch(intArray, counter - 50) == counter); - } - - /** - * java.util.Arrays#binarySearch(long[], long) - */ - public void test_binarySearch$JJ() { - // Test for method int java.util.Arrays.binarySearch(long [], long) - for (long counter = 0; counter < arraySize; counter++) - assertTrue("Binary search on long[] answered incorrect position", - Arrays.binarySearch(longArray, counter) == counter); - assertEquals("Binary search succeeded for value not present in array 1", - -1, Arrays.binarySearch(longArray, (long) -1)); - assertTrue( - "Binary search succeeded for value not present in array 2", - Arrays.binarySearch(longArray, (long) arraySize) == -(arraySize + 1)); - for (long counter = 0; counter < arraySize; counter++) - longArray[(int) counter] -= (long) 50; - for (long counter = 0; counter < arraySize; counter++) - assertTrue( - "Binary search on long[] involving negative numbers answered incorrect position", - Arrays.binarySearch(longArray, counter - (long) 50) == counter); - } - - /** - * java.util.Arrays#binarySearch(java.lang.Object[], - * java.lang.Object) - */ - public void test_binarySearch$Ljava_lang_ObjectLjava_lang_Object() { - // Test for method int java.util.Arrays.binarySearch(java.lang.Object - // [], java.lang.Object) - assertEquals( - "Binary search succeeded for non-comparable value in empty array", - -1, Arrays.binarySearch(new Object[] {}, new Object())); - assertEquals( - "Binary search succeeded for comparable value in empty array", - -1, Arrays.binarySearch(new Object[] {}, new Integer(-1))); - for (int counter = 0; counter < arraySize; counter++) - assertTrue( - "Binary search on Object[] answered incorrect position", - Arrays.binarySearch(objectArray, objArray[counter]) == counter); - assertEquals("Binary search succeeded for value not present in array 1", - -1, Arrays.binarySearch(objectArray, new Integer(-1))); - assertTrue( - "Binary search succeeded for value not present in array 2", - Arrays.binarySearch(objectArray, new Integer(arraySize)) == -(arraySize + 1)); - - String[] sArray = new String[]{"1", "2", "3", "4", ""}; - Object[] oArray = sArray; - - try { - Arrays.binarySearch(oArray, new Integer(10)); - fail("ClassCastException expected"); - } catch (ClassCastException e) { - //expected - } - } - - /** - * java.util.Arrays#binarySearch(java.lang.Object[], - * java.lang.Object, java.util.Comparator) - */ - public void test_binarySearch$Ljava_lang_ObjectLjava_lang_ObjectLjava_util_Comparator() { - // Test for method int java.util.Arrays.binarySearch(java.lang.Object - // [], java.lang.Object, java.util.Comparator) - Comparator comp = new ReversedIntegerComparator(); - for (int counter = 0; counter < arraySize; counter++) - objectArray[counter] = objArray[arraySize - counter - 1]; - assertTrue( - "Binary search succeeded for value not present in array 1", - Arrays.binarySearch(objectArray, new Integer(-1), comp) == -(arraySize + 1)); - assertEquals("Binary search succeeded for value not present in array 2", - -1, Arrays.binarySearch(objectArray, new Integer(arraySize), comp)); - for (int counter = 0; counter < arraySize; counter++) - assertTrue( - "Binary search on Object[] with custom comparator answered incorrect position", - Arrays.binarySearch(objectArray, objArray[counter], comp) == arraySize - - counter - 1); - } - - /** - * java.util.Arrays#binarySearch(short[], short) - */ - public void test_binarySearch$SS() { - // Test for method int java.util.Arrays.binarySearch(short [], short) - for (short counter = 0; counter < arraySize; counter++) - assertTrue("Binary search on short[] answered incorrect position", - Arrays.binarySearch(shortArray, counter) == counter); - assertEquals("Binary search succeeded for value not present in array 1", - -1, Arrays.binarySearch(intArray, (short) -1)); - assertTrue( - "Binary search succeeded for value not present in array 2", - Arrays.binarySearch(intArray, (short) arraySize) == -(arraySize + 1)); - for (short counter = 0; counter < arraySize; counter++) - shortArray[counter] -= 50; - for (short counter = 0; counter < arraySize; counter++) - assertTrue( - "Binary search on short[] involving negative numbers answered incorrect position", - Arrays.binarySearch(shortArray, (short) (counter - 50)) == counter); - } - - /** - * java.util.Arrays#fill(byte[], byte) - */ - public void test_fill$BB() { - // Test for method void java.util.Arrays.fill(byte [], byte) - - byte d[] = new byte[1000]; - Arrays.fill(d, Byte.MAX_VALUE); - for (int i = 0; i < d.length; i++) - assertTrue("Failed to fill byte array correctly", - d[i] == Byte.MAX_VALUE); - } - - /** - * java.util.Arrays#fill(byte[], int, int, byte) - */ - public void test_fill$BIIB() { - // Test for method void java.util.Arrays.fill(byte [], int, int, byte) - byte val = Byte.MAX_VALUE; - byte d[] = new byte[1000]; - Arrays.fill(d, 400, d.length, val); - for (int i = 0; i < 400; i++) - assertTrue("Filled elements not in range", !(d[i] == val)); - for (int i = 400; i < d.length; i++) - assertTrue("Failed to fill byte array correctly", d[i] == val); - - int result; - try { - Arrays.fill(new byte[2], 2, 1, (byte) 27); - result = 0; - } catch (ArrayIndexOutOfBoundsException e) { - result = 1; - } catch (IllegalArgumentException e) { - result = 2; - } - assertEquals("Wrong exception1", 2, result); - try { - Arrays.fill(new byte[2], -1, 1, (byte) 27); - result = 0; - } catch (ArrayIndexOutOfBoundsException e) { - result = 1; - } catch (IllegalArgumentException e) { - result = 2; - } - assertEquals("Wrong exception2", 1, result); - try { - Arrays.fill(new byte[2], 1, 4, (byte) 27); - result = 0; - } catch (ArrayIndexOutOfBoundsException e) { - result = 1; - } catch (IllegalArgumentException e) { - result = 2; - } - assertEquals("Wrong exception", 1, result); - } - - /** - * java.util.Arrays#fill(short[], short) - */ - public void test_fill$SS() { - // Test for method void java.util.Arrays.fill(short [], short) - - short d[] = new short[1000]; - Arrays.fill(d, Short.MAX_VALUE); - for (int i = 0; i < d.length; i++) - assertTrue("Failed to fill short array correctly", - d[i] == Short.MAX_VALUE); - } - - /** - * java.util.Arrays#fill(short[], int, int, short) - */ - public void test_fill$SIIS() { - // Test for method void java.util.Arrays.fill(short [], int, int, short) - short val = Short.MAX_VALUE; - short d[] = new short[1000]; - Arrays.fill(d, 400, d.length, val); - for (int i = 0; i < 400; i++) - assertTrue("Filled elements not in range", !(d[i] == val)); - for (int i = 400; i < d.length; i++) - assertTrue("Failed to fill short array correctly", d[i] == val); - - try { - Arrays.fill(d, 10, 0, val); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - Arrays.fill(d, -10, 0, val); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - //expected - } - - try { - Arrays.fill(d, 10, d.length+1, val); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - //expected - } - } - - /** - * java.util.Arrays#fill(char[], char) - */ - public void test_fill$CC() { - // Test for method void java.util.Arrays.fill(char [], char) - - char d[] = new char[1000]; - Arrays.fill(d, 'V'); - for (int i = 0; i < d.length; i++) - assertEquals("Failed to fill char array correctly", 'V', d[i]); - } - - /** - * java.util.Arrays#fill(char[], int, int, char) - */ - public void test_fill$CIIC() { - // Test for method void java.util.Arrays.fill(char [], int, int, char) - char val = 'T'; - char d[] = new char[1000]; - Arrays.fill(d, 400, d.length, val); - for (int i = 0; i < 400; i++) - assertTrue("Filled elements not in range", !(d[i] == val)); - for (int i = 400; i < d.length; i++) - assertTrue("Failed to fill char array correctly", d[i] == val); - - try { - Arrays.fill(d, 10, 0, val); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - Arrays.fill(d, -10, 0, val); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - //expected - } - - try { - Arrays.fill(d, 10, d.length+1, val); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - //expected - } - } - - /** - * java.util.Arrays#fill(int[], int) - */ - public void test_fill$II() { - // Test for method void java.util.Arrays.fill(int [], int) - - int d[] = new int[1000]; - Arrays.fill(d, Integer.MAX_VALUE); - for (int i = 0; i < d.length; i++) - assertTrue("Failed to fill int array correctly", - d[i] == Integer.MAX_VALUE); - } - - /** - * java.util.Arrays#fill(int[], int, int, int) - */ - public void test_fill$IIII() { - // Test for method void java.util.Arrays.fill(int [], int, int, int) - int val = Integer.MAX_VALUE; - int d[] = new int[1000]; - Arrays.fill(d, 400, d.length, val); - for (int i = 0; i < 400; i++) - assertTrue("Filled elements not in range", !(d[i] == val)); - for (int i = 400; i < d.length; i++) - assertTrue("Failed to fill int array correctly", d[i] == val); - - try { - Arrays.fill(d, 10, 0, val); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - Arrays.fill(d, -10, 0, val); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - //expected - } - - try { - Arrays.fill(d, 10, d.length+1, val); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - //expected - } - } - - /** - * java.util.Arrays#fill(long[], long) - */ - public void test_fill$JJ() { - // Test for method void java.util.Arrays.fill(long [], long) - - long d[] = new long[1000]; - Arrays.fill(d, Long.MAX_VALUE); - for (int i = 0; i < d.length; i++) - assertTrue("Failed to fill long array correctly", - d[i] == Long.MAX_VALUE); - } - - /** - * java.util.Arrays#fill(long[], int, int, long) - */ - public void test_fill$JIIJ() { - // Test for method void java.util.Arrays.fill(long [], int, int, long) - long d[] = new long[1000]; - Arrays.fill(d, 400, d.length, Long.MAX_VALUE); - for (int i = 0; i < 400; i++) - assertTrue("Filled elements not in range", !(d[i] == Long.MAX_VALUE)); - for (int i = 400; i < d.length; i++) - assertTrue("Failed to fill long array correctly", - d[i] == Long.MAX_VALUE); - - try { - Arrays.fill(d, 10, 0, Long.MIN_VALUE); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - Arrays.fill(d, -10, 0, Long.MAX_VALUE); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - //expected - } - - try { - Arrays.fill(d, 10, d.length+1, Long.MAX_VALUE); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - //expected - } - } - - /** - * java.util.Arrays#fill(float[], float) - */ - public void test_fill$FF() { - // Test for method void java.util.Arrays.fill(float [], float) - float d[] = new float[1000]; - Arrays.fill(d, Float.MAX_VALUE); - for (int i = 0; i < d.length; i++) - assertTrue("Failed to fill float array correctly", - d[i] == Float.MAX_VALUE); - } - - /** - * java.util.Arrays#fill(float[], int, int, float) - */ - public void test_fill$FIIF() { - // Test for method void java.util.Arrays.fill(float [], int, int, float) - float val = Float.MAX_VALUE; - float d[] = new float[1000]; - Arrays.fill(d, 400, d.length, val); - for (int i = 0; i < 400; i++) - assertTrue("Filled elements not in range", !(d[i] == val)); - for (int i = 400; i < d.length; i++) - assertTrue("Failed to fill float array correctly", d[i] == val); - - try { - Arrays.fill(d, 10, 0, val); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - Arrays.fill(d, -10, 0, val); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - //expected - } - - try { - Arrays.fill(d, 10, d.length+1, val); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - //expected - } - } - - /** - * java.util.Arrays#fill(double[], double) - */ - public void test_fill$DD() { - // Test for method void java.util.Arrays.fill(double [], double) - - double d[] = new double[1000]; - Arrays.fill(d, Double.MAX_VALUE); - for (int i = 0; i < d.length; i++) - assertTrue("Failed to fill double array correctly", - d[i] == Double.MAX_VALUE); - } - - /** - * java.util.Arrays#fill(double[], int, int, double) - */ - public void test_fill$DIID() { - // Test for method void java.util.Arrays.fill(double [], int, int, - // double) - double val = Double.MAX_VALUE; - double d[] = new double[1000]; - Arrays.fill(d, 400, d.length, val); - for (int i = 0; i < 400; i++) - assertTrue("Filled elements not in range", !(d[i] == val)); - for (int i = 400; i < d.length; i++) - assertTrue("Failed to fill double array correctly", d[i] == val); - - try { - Arrays.fill(d, 10, 0, val); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - Arrays.fill(d, -10, 0, val); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - //expected - } - - try { - Arrays.fill(d, 10, d.length+1, val); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - //expected - } - } - - /** - * java.util.Arrays#fill(boolean[], boolean) - */ - public void test_fill$ZZ() { - // Test for method void java.util.Arrays.fill(boolean [], boolean) - - boolean d[] = new boolean[1000]; - Arrays.fill(d, true); - for (int i = 0; i < d.length; i++) - assertTrue("Failed to fill boolean array correctly", d[i]); - } - - /** - * java.util.Arrays#fill(boolean[], int, int, boolean) - */ - public void test_fill$ZIIZ() { - // Test for method void java.util.Arrays.fill(boolean [], int, int, - // boolean) - boolean val = true; - boolean d[] = new boolean[1000]; - Arrays.fill(d, 400, d.length, val); - for (int i = 0; i < 400; i++) - assertTrue("Filled elements not in range", !(d[i] == val)); - for (int i = 400; i < d.length; i++) - assertTrue("Failed to fill boolean array correctly", d[i] == val); - - try { - Arrays.fill(d, 10, 0, val); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - Arrays.fill(d, -10, 0, val); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - //expected - } - - try { - Arrays.fill(d, 10, d.length+1, val); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - //expected - } - } - - /** - * java.util.Arrays#fill(java.lang.Object[], java.lang.Object) - */ - public void test_fill$Ljava_lang_ObjectLjava_lang_Object() { - // Test for method void java.util.Arrays.fill(java.lang.Object [], - // java.lang.Object) - Object val = new Object(); - Object d[] = new Object[1000]; - Arrays.fill(d, 0, d.length, val); - for (int i = 0; i < d.length; i++) - assertTrue("Failed to fill Object array correctly", d[i] == val); - } - - /** - * java.util.Arrays#fill(java.lang.Object[], int, int, - * java.lang.Object) - */ - public void test_fill$Ljava_lang_ObjectIILjava_lang_Object() { - // Test for method void java.util.Arrays.fill(java.lang.Object [], int, - // int, java.lang.Object) - Object val = new Object(); - Object d[] = new Object[1000]; - Arrays.fill(d, 400, d.length, val); - for (int i = 0; i < 400; i++) - assertTrue("Filled elements not in range", !(d[i] == val)); - for (int i = 400; i < d.length; i++) - assertTrue("Failed to fill Object array correctly", d[i] == val); - - Arrays.fill(d, 400, d.length, null); - for (int i = 400; i < d.length; i++) - assertNull("Failed to fill Object array correctly with nulls", - d[i]); - - try { - Arrays.fill(d, 10, 0, val); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - Arrays.fill(d, -10, 0, val); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - //expected - } - - try { - Arrays.fill(d, 10, d.length+1, val); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - //expected - } - } - - /** - * java.util.Arrays#equals(byte[], byte[]) - */ - public void test_equals$B$B() { - // Test for method boolean java.util.Arrays.equals(byte [], byte []) - byte d[] = new byte[1000]; - byte x[] = new byte[1000]; - Arrays.fill(d, Byte.MAX_VALUE); - Arrays.fill(x, Byte.MIN_VALUE); - assertTrue("Inequal arrays returned true", !Arrays.equals(d, x)); - Arrays.fill(x, Byte.MAX_VALUE); - assertTrue("equal arrays returned false", Arrays.equals(d, x)); - } - - /** - * java.util.Arrays#equals(short[], short[]) - */ - public void test_equals$S$S() { - // Test for method boolean java.util.Arrays.equals(short [], short []) - short d[] = new short[1000]; - short x[] = new short[1000]; - Arrays.fill(d, Short.MAX_VALUE); - Arrays.fill(x, Short.MIN_VALUE); - assertTrue("Inequal arrays returned true", !Arrays.equals(d, x)); - Arrays.fill(x, Short.MAX_VALUE); - assertTrue("equal arrays returned false", Arrays.equals(d, x)); - } - - /** - * java.util.Arrays#equals(char[], char[]) - */ - public void test_equals$C$C() { - // Test for method boolean java.util.Arrays.equals(char [], char []) - char d[] = new char[1000]; - char x[] = new char[1000]; - char c = 'T'; - Arrays.fill(d, c); - Arrays.fill(x, 'L'); - assertTrue("Inequal arrays returned true", !Arrays.equals(d, x)); - Arrays.fill(x, c); - assertTrue("equal arrays returned false", Arrays.equals(d, x)); - } - - /** - * java.util.Arrays#equals(int[], int[]) - */ - public void test_equals$I$I() { - // Test for method boolean java.util.Arrays.equals(int [], int []) - int d[] = new int[1000]; - int x[] = new int[1000]; - Arrays.fill(d, Integer.MAX_VALUE); - Arrays.fill(x, Integer.MIN_VALUE); - assertTrue("Inequal arrays returned true", !Arrays.equals(d, x)); - Arrays.fill(x, Integer.MAX_VALUE); - assertTrue("equal arrays returned false", Arrays.equals(d, x)); - - assertTrue("wrong result for null array1", !Arrays.equals(new int[2], - null)); - assertTrue("wrong result for null array2", !Arrays.equals(null, - new int[2])); - } - - /** - * java.util.Arrays#equals(long[], long[]) - */ - public void test_equals$J$J() { - // Test for method boolean java.util.Arrays.equals(long [], long []) - long d[] = new long[1000]; - long x[] = new long[1000]; - Arrays.fill(d, Long.MAX_VALUE); - Arrays.fill(x, Long.MIN_VALUE); - assertTrue("Inequal arrays returned true", !Arrays.equals(d, x)); - Arrays.fill(x, Long.MAX_VALUE); - assertTrue("equal arrays returned false", Arrays.equals(d, x)); - - assertTrue("should be false", !Arrays.equals( - new long[] { 0x100000000L }, new long[] { 0x200000000L })); - - } - - /** - * java.util.Arrays#equals(float[], float[]) - */ - public void test_equals$F$F() { - // Test for method boolean java.util.Arrays.equals(float [], float []) - float d[] = new float[1000]; - float x[] = new float[1000]; - Arrays.fill(d, Float.MAX_VALUE); - Arrays.fill(x, Float.MIN_VALUE); - assertTrue("Inequal arrays returned true", !Arrays.equals(d, x)); - Arrays.fill(x, Float.MAX_VALUE); - assertTrue("equal arrays returned false", Arrays.equals(d, x)); - - assertTrue("NaN not equals", Arrays.equals(new float[] { Float.NaN }, - new float[] { Float.NaN })); - assertTrue("0f equals -0f", !Arrays.equals(new float[] { 0f }, - new float[] { -0f })); - } - - /** - * java.util.Arrays#equals(double[], double[]) - */ - public void test_equals$D$D() { - // Test for method boolean java.util.Arrays.equals(double [], double []) - double d[] = new double[1000]; - double x[] = new double[1000]; - Arrays.fill(d, Double.MAX_VALUE); - Arrays.fill(x, Double.MIN_VALUE); - assertTrue("Inequal arrays returned true", !Arrays.equals(d, x)); - Arrays.fill(x, Double.MAX_VALUE); - assertTrue("equal arrays returned false", Arrays.equals(d, x)); - - assertTrue("should be false", !Arrays.equals(new double[] { 1.0 }, - new double[] { 2.0 })); - - assertTrue("NaN not equals", Arrays.equals(new double[] { Double.NaN }, - new double[] { Double.NaN })); - assertTrue("0d equals -0d", !Arrays.equals(new double[] { 0d }, - new double[] { -0d })); - } - - /** - * java.util.Arrays#equals(boolean[], boolean[]) - */ - public void test_equals$Z$Z() { - // Test for method boolean java.util.Arrays.equals(boolean [], boolean - // []) - boolean d[] = new boolean[1000]; - boolean x[] = new boolean[1000]; - Arrays.fill(d, true); - Arrays.fill(x, false); - assertTrue("Inequal arrays returned true", !Arrays.equals(d, x)); - Arrays.fill(x, true); - assertTrue("equal arrays returned false", Arrays.equals(d, x)); - } - - /** - * java.util.Arrays#equals(java.lang.Object[], java.lang.Object[]) - */ - public void test_equals$Ljava_lang_Object$Ljava_lang_Object() { - // Test for method boolean java.util.Arrays.equals(java.lang.Object [], - // java.lang.Object []) - Object d[] = new Object[1000]; - Object x[] = new Object[1000]; - Object o = new Object(); - Arrays.fill(d, o); - Arrays.fill(x, new Object()); - assertTrue("Inequal arrays returned true", !Arrays.equals(d, x)); - Arrays.fill(x, o); - d[50] = null; - x[50] = null; - assertTrue("equal arrays returned false", Arrays.equals(d, x)); - } - - /** - * java.util.Arrays#sort(byte[]) - */ - public void test_sort$B() { - // Test for method void java.util.Arrays.sort(byte []) - byte[] reversedArray = new byte[arraySize]; - for (int counter = 0; counter < arraySize; counter++) - reversedArray[counter] = (byte) (arraySize - counter - 1); - Arrays.sort(reversedArray); - for (int counter = 0; counter < arraySize; counter++) - assertTrue("Resulting array not sorted", - reversedArray[counter] == (byte) counter); - } - - /** - * java.util.Arrays#sort(byte[], int, int) - */ - public void test_sort$BII() { - // Test for method void java.util.Arrays.sort(byte [], int, int) - int startIndex = arraySize / 4; - int endIndex = 3 * arraySize / 4; - byte[] reversedArray = new byte[arraySize]; - byte[] originalReversedArray = new byte[arraySize]; - for (int counter = 0; counter < arraySize; counter++) { - reversedArray[counter] = (byte) (arraySize - counter - 1); - originalReversedArray[counter] = reversedArray[counter]; - } - Arrays.sort(reversedArray, startIndex, endIndex); - for (int counter = 0; counter < startIndex; counter++) - assertTrue("Array modified outside of bounds", - reversedArray[counter] == originalReversedArray[counter]); - for (int counter = startIndex; counter < endIndex - 1; counter++) - assertTrue("Array not sorted within bounds", - reversedArray[counter] <= reversedArray[counter + 1]); - for (int counter = endIndex; counter < arraySize; counter++) - assertTrue("Array modified outside of bounds", - reversedArray[counter] == originalReversedArray[counter]); - - //exception testing - try { - Arrays.sort(reversedArray, startIndex + 1, startIndex); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException ignore) { - } - - try { - Arrays.sort(reversedArray, -1, startIndex); - fail("ArrayIndexOutOfBoundsException expected (1)"); - } catch (ArrayIndexOutOfBoundsException ignore) { - } - - try { - Arrays.sort(reversedArray, startIndex, reversedArray.length + 1); - fail("ArrayIndexOutOfBoundsException expected (2)"); - } catch (ArrayIndexOutOfBoundsException ignore) { - } - } - - /** - * java.util.Arrays#sort(char[]) - */ - public void test_sort$C() { - // Test for method void java.util.Arrays.sort(char []) - char[] reversedArray = new char[arraySize]; - for (int counter = 0; counter < arraySize; counter++) - reversedArray[counter] = (char) (arraySize - counter - 1); - Arrays.sort(reversedArray); - for (int counter = 0; counter < arraySize; counter++) - assertTrue("Resulting array not sorted", - reversedArray[counter] == (char) counter); - - } - - /** - * java.util.Arrays#sort(char[], int, int) - */ - public void test_sort$CII() { - // Test for method void java.util.Arrays.sort(char [], int, int) - int startIndex = arraySize / 4; - int endIndex = 3 * arraySize / 4; - char[] reversedArray = new char[arraySize]; - char[] originalReversedArray = new char[arraySize]; - for (int counter = 0; counter < arraySize; counter++) { - reversedArray[counter] = (char) (arraySize - counter - 1); - originalReversedArray[counter] = reversedArray[counter]; - } - Arrays.sort(reversedArray, startIndex, endIndex); - for (int counter = 0; counter < startIndex; counter++) - assertTrue("Array modified outside of bounds", - reversedArray[counter] == originalReversedArray[counter]); - for (int counter = startIndex; counter < endIndex - 1; counter++) - assertTrue("Array not sorted within bounds", - reversedArray[counter] <= reversedArray[counter + 1]); - for (int counter = endIndex; counter < arraySize; counter++) - assertTrue("Array modified outside of bounds", - reversedArray[counter] == originalReversedArray[counter]); - - //exception testing - try { - Arrays.sort(reversedArray, startIndex + 1, startIndex); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException ignore) { - } - - try { - Arrays.sort(reversedArray, -1, startIndex); - fail("ArrayIndexOutOfBoundsException expected (1)"); - } catch (ArrayIndexOutOfBoundsException ignore) { - } - - try { - Arrays.sort(reversedArray, startIndex, reversedArray.length + 1); - fail("ArrayIndexOutOfBoundsException expected (2)"); - } catch (ArrayIndexOutOfBoundsException ignore) { - } - } - - /** - * java.util.Arrays#sort(double[]) - */ - public void test_sort$D() { - // Test for method void java.util.Arrays.sort(double []) - double[] reversedArray = new double[arraySize]; - for (int counter = 0; counter < arraySize; counter++) - reversedArray[counter] = (double) (arraySize - counter - 1); - Arrays.sort(reversedArray); - for (int counter = 0; counter < arraySize; counter++) - assertTrue("Resulting array not sorted", - reversedArray[counter] == (double) counter); - - double[] specials1 = new double[] { Double.NaN, Double.MAX_VALUE, - Double.MIN_VALUE, 0d, -0d, Double.POSITIVE_INFINITY, - Double.NEGATIVE_INFINITY }; - double[] specials2 = new double[] { 0d, Double.POSITIVE_INFINITY, -0d, - Double.NEGATIVE_INFINITY, Double.MIN_VALUE, Double.NaN, - Double.MAX_VALUE }; - double[] answer = new double[] { Double.NEGATIVE_INFINITY, -0d, 0d, - Double.MIN_VALUE, Double.MAX_VALUE, Double.POSITIVE_INFINITY, - Double.NaN }; - - Arrays.sort(specials1); - Object[] print1 = new Object[specials1.length]; - for (int i = 0; i < specials1.length; i++) - print1[i] = new Double(specials1[i]); - assertTrue("specials sort incorrectly 1: " + Arrays.asList(print1), - Arrays.equals(specials1, answer)); - - Arrays.sort(specials2); - Object[] print2 = new Object[specials2.length]; - for (int i = 0; i < specials2.length; i++) - print2[i] = new Double(specials2[i]); - assertTrue("specials sort incorrectly 2: " + Arrays.asList(print2), - Arrays.equals(specials2, answer)); - } - - /** - * java.util.Arrays#sort(double[], int, int) - */ - public void test_sort$DII() { - // Test for method void java.util.Arrays.sort(double [], int, int) - int startIndex = arraySize / 4; - int endIndex = 3 * arraySize / 4; - double[] reversedArray = new double[arraySize]; - double[] originalReversedArray = new double[arraySize]; - for (int counter = 0; counter < arraySize; counter++) { - reversedArray[counter] = (double) (arraySize - counter - 1); - originalReversedArray[counter] = reversedArray[counter]; - } - Arrays.sort(reversedArray, startIndex, endIndex); - for (int counter = 0; counter < startIndex; counter++) - assertTrue("Array modified outside of bounds", - reversedArray[counter] == originalReversedArray[counter]); - for (int counter = startIndex; counter < endIndex - 1; counter++) - assertTrue("Array not sorted within bounds", - reversedArray[counter] <= reversedArray[counter + 1]); - for (int counter = endIndex; counter < arraySize; counter++) - assertTrue("Array modified outside of bounds", - reversedArray[counter] == originalReversedArray[counter]); - - //exception testing - try { - Arrays.sort(reversedArray, startIndex + 1, startIndex); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException ignore) { - } - - try { - Arrays.sort(reversedArray, -1, startIndex); - fail("ArrayIndexOutOfBoundsException expected (1)"); - } catch (ArrayIndexOutOfBoundsException ignore) { - } - - try { - Arrays.sort(reversedArray, startIndex, reversedArray.length + 1); - fail("ArrayIndexOutOfBoundsException expected (2)"); - } catch (ArrayIndexOutOfBoundsException ignore) { - } - } - - /** - * java.util.Arrays#sort(float[]) - */ - public void test_sort$F() { - // Test for method void java.util.Arrays.sort(float []) - float[] reversedArray = new float[arraySize]; - for (int counter = 0; counter < arraySize; counter++) - reversedArray[counter] = (float) (arraySize - counter - 1); - Arrays.sort(reversedArray); - for (int counter = 0; counter < arraySize; counter++) - assertTrue("Resulting array not sorted", - reversedArray[counter] == (float) counter); - - float[] specials1 = new float[] { Float.NaN, Float.MAX_VALUE, - Float.MIN_VALUE, 0f, -0f, Float.POSITIVE_INFINITY, - Float.NEGATIVE_INFINITY }; - float[] specials2 = new float[] { 0f, Float.POSITIVE_INFINITY, -0f, - Float.NEGATIVE_INFINITY, Float.MIN_VALUE, Float.NaN, - Float.MAX_VALUE }; - float[] answer = new float[] { Float.NEGATIVE_INFINITY, -0f, 0f, - Float.MIN_VALUE, Float.MAX_VALUE, Float.POSITIVE_INFINITY, - Float.NaN }; - - Arrays.sort(specials1); - Object[] print1 = new Object[specials1.length]; - for (int i = 0; i < specials1.length; i++) - print1[i] = new Float(specials1[i]); - assertTrue("specials sort incorrectly 1: " + Arrays.asList(print1), - Arrays.equals(specials1, answer)); - - Arrays.sort(specials2); - Object[] print2 = new Object[specials2.length]; - for (int i = 0; i < specials2.length; i++) - print2[i] = new Float(specials2[i]); - assertTrue("specials sort incorrectly 2: " + Arrays.asList(print2), - Arrays.equals(specials2, answer)); - } - - /** - * java.util.Arrays#sort(float[], int, int) - */ - public void test_sort$FII() { - // Test for method void java.util.Arrays.sort(float [], int, int) - int startIndex = arraySize / 4; - int endIndex = 3 * arraySize / 4; - float[] reversedArray = new float[arraySize]; - float[] originalReversedArray = new float[arraySize]; - for (int counter = 0; counter < arraySize; counter++) { - reversedArray[counter] = (float) (arraySize - counter - 1); - originalReversedArray[counter] = reversedArray[counter]; - } - Arrays.sort(reversedArray, startIndex, endIndex); - for (int counter = 0; counter < startIndex; counter++) - assertTrue("Array modified outside of bounds", - reversedArray[counter] == originalReversedArray[counter]); - for (int counter = startIndex; counter < endIndex - 1; counter++) - assertTrue("Array not sorted within bounds", - reversedArray[counter] <= reversedArray[counter + 1]); - for (int counter = endIndex; counter < arraySize; counter++) - assertTrue("Array modified outside of bounds", - reversedArray[counter] == originalReversedArray[counter]); - - //exception testing - try { - Arrays.sort(reversedArray, startIndex + 1, startIndex); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException ignore) { - } - - try { - Arrays.sort(reversedArray, -1, startIndex); - fail("ArrayIndexOutOfBoundsException expected (1)"); - } catch (ArrayIndexOutOfBoundsException ignore) { - } - - try { - Arrays.sort(reversedArray, startIndex, reversedArray.length + 1); - fail("ArrayIndexOutOfBoundsException expected (2)"); - } catch (ArrayIndexOutOfBoundsException ignore) { - } - } - - /** - * java.util.Arrays#sort(int[]) - */ - public void test_sort$I() { - // Test for method void java.util.Arrays.sort(int []) - int[] reversedArray = new int[arraySize]; - for (int counter = 0; counter < arraySize; counter++) - reversedArray[counter] = arraySize - counter - 1; - Arrays.sort(reversedArray); - for (int counter = 0; counter < arraySize; counter++) - assertTrue("Resulting array not sorted", - reversedArray[counter] == counter); - } - - /** - * java.util.Arrays#sort(int[], int, int) - */ - public void test_sort$III() { - // Test for method void java.util.Arrays.sort(int [], int, int) - int startIndex = arraySize / 4; - int endIndex = 3 * arraySize / 4; - int[] reversedArray = new int[arraySize]; - int[] originalReversedArray = new int[arraySize]; - for (int counter = 0; counter < arraySize; counter++) { - reversedArray[counter] = arraySize - counter - 1; - originalReversedArray[counter] = reversedArray[counter]; - } - Arrays.sort(reversedArray, startIndex, endIndex); - for (int counter = 0; counter < startIndex; counter++) - assertTrue("Array modified outside of bounds", - reversedArray[counter] == originalReversedArray[counter]); - for (int counter = startIndex; counter < endIndex - 1; counter++) - assertTrue("Array not sorted within bounds", - reversedArray[counter] <= reversedArray[counter + 1]); - for (int counter = endIndex; counter < arraySize; counter++) - assertTrue("Array modified outside of bounds", - reversedArray[counter] == originalReversedArray[counter]); - - //exception testing - try { - Arrays.sort(reversedArray, startIndex + 1, startIndex); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException ignore) { - } - - try { - Arrays.sort(reversedArray, -1, startIndex); - fail("ArrayIndexOutOfBoundsException expected (1)"); - } catch (ArrayIndexOutOfBoundsException ignore) { - } - - try { - Arrays.sort(reversedArray, startIndex, reversedArray.length + 1); - fail("ArrayIndexOutOfBoundsException expected (2)"); - } catch (ArrayIndexOutOfBoundsException ignore) { - } - } - - /** - * java.util.Arrays#sort(long[]) - */ - public void test_sort$J() { - // Test for method void java.util.Arrays.sort(long []) - long[] reversedArray = new long[arraySize]; - for (int counter = 0; counter < arraySize; counter++) - reversedArray[counter] = (long) (arraySize - counter - 1); - Arrays.sort(reversedArray); - for (int counter = 0; counter < arraySize; counter++) - assertTrue("Resulting array not sorted", - reversedArray[counter] == (long) counter); - - } - - /** - * java.util.Arrays#sort(long[], int, int) - */ - public void test_sort$JII() { - // Test for method void java.util.Arrays.sort(long [], int, int) - int startIndex = arraySize / 4; - int endIndex = 3 * arraySize / 4; - long[] reversedArray = new long[arraySize]; - long[] originalReversedArray = new long[arraySize]; - for (int counter = 0; counter < arraySize; counter++) { - reversedArray[counter] = (long) (arraySize - counter - 1); - originalReversedArray[counter] = reversedArray[counter]; - } - Arrays.sort(reversedArray, startIndex, endIndex); - for (int counter = 0; counter < startIndex; counter++) - assertTrue("Array modified outside of bounds", - reversedArray[counter] == originalReversedArray[counter]); - for (int counter = startIndex; counter < endIndex - 1; counter++) - assertTrue("Array not sorted within bounds", - reversedArray[counter] <= reversedArray[counter + 1]); - for (int counter = endIndex; counter < arraySize; counter++) - assertTrue("Array modified outside of bounds", - reversedArray[counter] == originalReversedArray[counter]); - - //exception testing - try { - Arrays.sort(reversedArray, startIndex + 1, startIndex); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException ignore) { - } - - try { - Arrays.sort(reversedArray, -1, startIndex); - fail("ArrayIndexOutOfBoundsException expected (1)"); - } catch (ArrayIndexOutOfBoundsException ignore) { - } - - try { - Arrays.sort(reversedArray, startIndex, reversedArray.length + 1); - fail("ArrayIndexOutOfBoundsException expected (2)"); - } catch (ArrayIndexOutOfBoundsException ignore) { - } - } - - /** - * java.util.Arrays#sort(java.lang.Object[]) - */ - public void test_sort$Ljava_lang_Object() { - // Test for method void java.util.Arrays.sort(java.lang.Object []) - Object[] reversedArray = new Object[arraySize]; - for (int counter = 0; counter < arraySize; counter++) - reversedArray[counter] = objectArray[arraySize - counter - 1]; - Arrays.sort(reversedArray); - for (int counter = 0; counter < arraySize; counter++) - assertTrue("Resulting array not sorted", - reversedArray[counter] == objectArray[counter]); - - Arrays.fill(reversedArray, 0, reversedArray.length/2, "String"); - Arrays.fill(reversedArray, reversedArray.length/2, reversedArray.length, new Integer(1)); - - try { - Arrays.sort(reversedArray); - fail("ClassCastException expected"); - } catch (ClassCastException e) { - //expected - } - } - - /** - * java.util.Arrays#sort(java.lang.Object[], int, int) - */ - public void test_sort$Ljava_lang_ObjectII() { - // Test for method void java.util.Arrays.sort(java.lang.Object [], int, - // int) - int startIndex = arraySize / 4; - int endIndex = 3 * arraySize / 4; - Object[] reversedArray = new Object[arraySize]; - Object[] originalReversedArray = new Object[arraySize]; - for (int counter = 0; counter < arraySize; counter++) { - reversedArray[counter] = objectArray[arraySize - counter - 1]; - originalReversedArray[counter] = reversedArray[counter]; - } - Arrays.sort(reversedArray, startIndex, endIndex); - for (int counter = 0; counter < startIndex; counter++) - assertTrue("Array modified outside of bounds", - reversedArray[counter] == originalReversedArray[counter]); - for (int counter = startIndex; counter < endIndex - 1; counter++) - assertTrue("Array not sorted within bounds", - ((Comparable) reversedArray[counter]) - .compareTo(reversedArray[counter + 1]) <= 0); - for (int counter = endIndex; counter < arraySize; counter++) - assertTrue("Array modified outside of bounds", - reversedArray[counter] == originalReversedArray[counter]); - - //exception testing - try { - Arrays.sort(reversedArray, startIndex + 1, startIndex); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException ignore) { - } - - try { - Arrays.sort(reversedArray, -1, startIndex); - fail("ArrayIndexOutOfBoundsException expected (1)"); - } catch (ArrayIndexOutOfBoundsException ignore) { - } - - try { - Arrays.sort(reversedArray, startIndex, reversedArray.length + 1); - fail("ArrayIndexOutOfBoundsException expected (2)"); - } catch (ArrayIndexOutOfBoundsException ignore) { - } - - Arrays.fill(reversedArray, 0, reversedArray.length/2, "String"); - Arrays.fill(reversedArray, reversedArray.length/2, reversedArray.length, new Integer(1)); - - try { - Arrays.sort(reversedArray, reversedArray.length/4, 3*reversedArray.length/4); - fail("ClassCastException expected"); - } catch (ClassCastException e) { - //expected - } - - Arrays.sort(reversedArray, 0, reversedArray.length/4); - Arrays.sort(reversedArray, 3*reversedArray.length/4, reversedArray.length); - } - - /** - * java.util.Arrays#sort(java.lang.Object[], int, int, - * java.util.Comparator) - */ - public void test_sort$Ljava_lang_ObjectIILjava_util_Comparator() { - // Test for method void java.util.Arrays.sort(java.lang.Object [], int, - // int, java.util.Comparator) - int startIndex = arraySize / 4; - int endIndex = 3 * arraySize / 4; - ReversedIntegerComparator comp = new ReversedIntegerComparator(); - Object[] originalArray = new Object[arraySize]; - for (int counter = 0; counter < arraySize; counter++) - originalArray[counter] = objectArray[counter]; - Arrays.sort(objectArray, startIndex, endIndex, comp); - for (int counter = 0; counter < startIndex; counter++) - assertTrue("Array modified outside of bounds", - objectArray[counter] == originalArray[counter]); - for (int counter = startIndex; counter < endIndex - 1; counter++) - assertTrue("Array not sorted within bounds", comp.compare( - objectArray[counter], objectArray[counter + 1]) <= 0); - for (int counter = endIndex; counter < arraySize; counter++) - assertTrue("Array modified outside of bounds", - objectArray[counter] == originalArray[counter]); - - Arrays.fill(originalArray, 0, originalArray.length/2, "String"); - Arrays.fill(originalArray, originalArray.length/2, originalArray.length, new Integer(1)); - - try { - Arrays.sort(originalArray, startIndex, endIndex, comp); - fail("ClassCastException expected"); - } catch (ClassCastException e) { - //expected - } - - Arrays.sort(originalArray, endIndex, originalArray.length, comp); - - try { - Arrays.sort(originalArray, endIndex, originalArray.length + 1, comp); - fail("ArrayIndexOutOfBoundsException expected"); - } catch(ArrayIndexOutOfBoundsException e) { - //expected - } - - try { - Arrays.sort(originalArray, -1, startIndex, comp); - fail("ArrayIndexOutOfBoundsException expected"); - } catch(ArrayIndexOutOfBoundsException e) { - //expected - } - - try { - Arrays.sort(originalArray, originalArray.length, endIndex, comp); - fail("IllegalArgumentException expected"); - } catch(IllegalArgumentException e) { - //expected - } - } - - /** - * java.util.Arrays#sort(java.lang.Object[], java.util.Comparator) - */ - public void test_sort$Ljava_lang_ObjectLjava_util_Comparator() { - // Test for method void java.util.Arrays.sort(java.lang.Object [], - // java.util.Comparator) - ReversedIntegerComparator comp = new ReversedIntegerComparator(); - Arrays.sort(objectArray, comp); - for (int counter = 0; counter < arraySize - 1; counter++) - assertTrue("Array not sorted correctly with custom comparator", - comp - .compare(objectArray[counter], - objectArray[counter + 1]) <= 0); - - Arrays.fill(objectArray, 0, objectArray.length/2, "String"); - Arrays.fill(objectArray, objectArray.length/2, objectArray.length, new Integer(1)); - - try { - Arrays.sort(objectArray, comp); - fail("ClassCastException expected"); - } catch (ClassCastException e) { - //expected - } - } - - /** - * java.util.Arrays#sort(short[]) - */ - public void test_sort$S() { - // Test for method void java.util.Arrays.sort(short []) - short[] reversedArray = new short[arraySize]; - for (int counter = 0; counter < arraySize; counter++) - reversedArray[counter] = (short) (arraySize - counter - 1); - Arrays.sort(reversedArray); - for (int counter = 0; counter < arraySize; counter++) - assertTrue("Resulting array not sorted", - reversedArray[counter] == (short) counter); - } - - /** - * java.util.Arrays#sort(short[], int, int) - */ - public void test_sort$SII() { - // Test for method void java.util.Arrays.sort(short [], int, int) - int startIndex = arraySize / 4; - int endIndex = 3 * arraySize / 4; - short[] reversedArray = new short[arraySize]; - short[] originalReversedArray = new short[arraySize]; - for (int counter = 0; counter < arraySize; counter++) { - reversedArray[counter] = (short) (arraySize - counter - 1); - originalReversedArray[counter] = reversedArray[counter]; - } - Arrays.sort(reversedArray, startIndex, endIndex); - for (int counter = 0; counter < startIndex; counter++) - assertTrue("Array modified outside of bounds", - reversedArray[counter] == originalReversedArray[counter]); - for (int counter = startIndex; counter < endIndex - 1; counter++) - assertTrue("Array not sorted within bounds", - reversedArray[counter] <= reversedArray[counter + 1]); - for (int counter = endIndex; counter < arraySize; counter++) - assertTrue("Array modified outside of bounds", - reversedArray[counter] == originalReversedArray[counter]); - - //exception testing - try { - Arrays.sort(reversedArray, startIndex + 1, startIndex); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException ignore) { - } - - try { - Arrays.sort(reversedArray, -1, startIndex); - fail("ArrayIndexOutOfBoundsException expected (1)"); - } catch (ArrayIndexOutOfBoundsException ignore) { - } - - try { - Arrays.sort(reversedArray, startIndex, reversedArray.length + 1); - fail("ArrayIndexOutOfBoundsException expected (2)"); - } catch (ArrayIndexOutOfBoundsException ignore) { - } - } - - /** - * java.util.Arrays#sort(byte[], int, int) - */ - public void test_java_util_Arrays_sort_byte_array_NPE() { - byte[] byte_array_null = null; - try { - java.util.Arrays.sort(byte_array_null); - fail("Should throw java.lang.NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - try { - // Regression for HARMONY-378 - java.util.Arrays.sort(byte_array_null, (int) -1, (int) 1); - fail("Should throw java.lang.NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - } - - /** - * java.util.Arrays#sort(char[], int, int) - */ - public void test_java_util_Arrays_sort_char_array_NPE() { - char[] char_array_null = null; - try { - java.util.Arrays.sort(char_array_null); - fail("Should throw java.lang.NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - try { - // Regression for HARMONY-378 - java.util.Arrays.sort(char_array_null, (int) -1, (int) 1); - fail("Should throw java.lang.NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - } - - /** - * java.util.Arrays#sort(double[], int, int) - */ - public void test_java_util_Arrays_sort_double_array_NPE() { - double[] double_array_null = null; - try { - java.util.Arrays.sort(double_array_null); - fail("Should throw java.lang.NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - try { - // Regression for HARMONY-378 - java.util.Arrays.sort(double_array_null, (int) -1, (int) 1); - fail("Should throw java.lang.NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - } - - /** - * java.util.Arrays#sort(float[], int, int) - */ - public void test_java_util_Arrays_sort_float_array_NPE() { - float[] float_array_null = null; - try { - java.util.Arrays.sort(float_array_null); - fail("Should throw java.lang.NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - try { - // Regression for HARMONY-378 - java.util.Arrays.sort(float_array_null, (int) -1, (int) 1); - fail("Should throw java.lang.NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - } - - /** - * java.util.Arrays#sort(int[], int, int) - */ - public void test_java_util_Arrays_sort_int_array_NPE() { - int[] int_array_null = null; - try { - java.util.Arrays.sort(int_array_null); - fail("Should throw java.lang.NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - try { - // Regression for HARMONY-378 - java.util.Arrays.sort(int_array_null, (int) -1, (int) 1); - fail("Should throw java.lang.NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - } - - /** - * java.util.Arrays#sort(Object[], int, int) - */ - public void test_java_util_Arrays_sort_object_array_NPE() { - Object[] object_array_null = null; - try { - java.util.Arrays.sort(object_array_null); - fail("Should throw java.lang.NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - try { - // Regression for HARMONY-378 - java.util.Arrays.sort(object_array_null, (int) -1, (int) 1); - fail("Should throw java.lang.NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - try { - // Regression for HARMONY-378 - java.util.Arrays.sort(object_array_null, (int) -1, (int) 1, null); - fail("Should throw java.lang.NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - } - - /** - * java.util.Arrays#sort(long[], int, int) - */ - public void test_java_util_Arrays_sort_long_array_NPE() { - long[] long_array_null = null; - try { - java.util.Arrays.sort(long_array_null); - fail("Should throw java.lang.NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - try { - // Regression for HARMONY-378 - java.util.Arrays.sort(long_array_null, (int) -1, (int) 1); - fail("Should throw java.lang.NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - } - - /** - * java.util.Arrays#sort(short[], int, int) - */ - public void test_java_util_Arrays_sort_short_array_NPE() { - short[] short_array_null = null; - try { - java.util.Arrays.sort(short_array_null); - fail("Should throw java.lang.NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - try { - // Regression for HARMONY-378 - java.util.Arrays.sort(short_array_null, (int) -1, (int) 1); - fail("Should throw java.lang.NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - } - - // Lenghts of arrays to test in test_sort; - private static final int[] LENGTHS = { 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 100, 1000, 10000 }; - - /** - * java.util.Arrays#sort() - */ - public void test_sort() { - for (int len : LENGTHS) { - PrimitiveTypeArrayBuilder.reset(); - int[] golden = new int[len]; - for (int m = 1; m < 2 * len; m *= 2) { - for (PrimitiveTypeArrayBuilder builder : PrimitiveTypeArrayBuilder.values()) { - builder.build(golden, m); - int[] test = golden.clone(); - - for (PrimitiveTypeConverter converter : PrimitiveTypeConverter.values()) { - Object convertedGolden = converter.convert(golden); - Object convertedTest = converter.convert(test); - sort(convertedTest); - checkSorted(convertedTest); - assertEquals(checkSum(convertedGolden), checkSum(convertedTest)); - } - } - } - } - } - - private void sort(Object array) { - if (array instanceof int[]) { - Arrays.sort((int[]) array); - } - else if (array instanceof long[]) { - Arrays.sort((long[]) array); - } else if (array instanceof short[]) { - Arrays.sort((short[]) array); - } else if (array instanceof byte[]) { - Arrays.sort((byte[]) array); - } else if (array instanceof char[]) { - Arrays.sort((char[]) array); - } else if (array instanceof float[]) { - Arrays.sort((float[]) array); - } else if (array instanceof double[]) { - Arrays.sort((double[]) array); - } else { - fail("Unknow type of array: " + array.getClass()); - } - } - - private void checkSorted(Object array) { - if (array instanceof int[]) { - checkSorted((int[]) array); - } else if (array instanceof long[]) { - checkSorted((long[]) array); - } else if (array instanceof short[]) { - checkSorted((short[]) array); - } else if (array instanceof byte[]) { - checkSorted((byte[]) array); - } else if (array instanceof char[]) { - checkSorted((char[]) array); - } else if (array instanceof float[]) { - checkSorted((float[]) array); - } else if (array instanceof double[]) { - checkSorted((double[]) array); - } else { - fail("Unknow type of array: " + array.getClass()); - } - } - - private void checkSorted(int[] a) { - for (int i = 0; i < a.length - 1; i++) { - if (a[i] > a[i + 1]) { - orderFail(i, "" + a[i], "" + a[i + 1]); - } - } - } - - private void checkSorted(long[] a) { - for (int i = 0; i < a.length - 1; i++) { - if (a[i] > a[i + 1]) { - orderFail(i, "" + a[i], "" + a[i + 1]); - } - } - } - - private void checkSorted(short[] a) { - for (int i = 0; i < a.length - 1; i++) { - if (a[i] > a[i + 1]) { - orderFail(i, "" + a[i], "" + a[i + 1]); - } - } - } - - private void checkSorted(byte[] a) { - for (int i = 0; i < a.length - 1; i++) { - if (a[i] > a[i + 1]) { - orderFail(i, "" + a[i], "" + a[i + 1]); - } - } - } - - private void checkSorted(char[] a) { - for (int i = 0; i < a.length - 1; i++) { - if (a[i] > a[i + 1]) { - orderFail(i, "" + a[i], "" + a[i + 1]); - } - } - } - - private void checkSorted(float[] a) { - for (int i = 0; i < a.length - 1; i++) { - if (a[i] > a[i + 1]) { - orderFail(i, "" + a[i], "" + a[i + 1]); - } - } - } - - private void checkSorted(double[] a) { - for (int i = 0; i < a.length - 1; i++) { - if (a[i] > a[i + 1]) { - orderFail(i, "" + a[i], "" + a[i + 1]); - } - } - } - - - private void orderFail(int index, String value1, String value2) { - fail("Array is not sorted at " + index + "-th position: " + value1 + " and " + value2); - } - - private int checkSum(Object array) { - if (array instanceof int[]) { - return checkSum((int[]) array); - } else if (array instanceof long[]) { - return checkSum((long[]) array); - } else if (array instanceof short[]) { - return checkSum((short[]) array); - } else if (array instanceof byte[]) { - return checkSum((byte[]) array); - } else if (array instanceof char[]) { - return checkSum((char[]) array); - } else if (array instanceof float[]) { - return checkSum((float[]) array); - } else if (array instanceof double[]) { - return checkSum((double[]) array); - } else { - fail("Unknow type of array: " + array.getClass()); - } - throw new AssertionError(); // Needed to shut up compiler - } - - private int checkSum(int[] a) { - int checkSum = 0; - - for (int e : a) { - checkSum ^= e; // xor - } - return checkSum; - } - - private int checkSum(long[] a) { - long checkSum = 0; - - for (long e : a) { - checkSum ^= e; // xor - } - return (int) checkSum; - } - - private int checkSum(short[] a) { - short checkSum = 0; - - for (short e : a) { - checkSum ^= e; // xor - } - return (int) checkSum; - } - - private int checkSum(byte[] a) { - byte checkSum = 0; - - for (byte e : a) { - checkSum ^= e; // xor - } - return (int) checkSum; - } - - private int checkSum(char[] a) { - char checkSum = 0; - - for (char e : a) { - checkSum ^= e; // xor - } - return (int) checkSum; - } - - private int checkSum(float[] a) { - int checkSum = 0; - - for (float e : a) { - checkSum ^= (int) e; // xor - } - return checkSum; - } - - private int checkSum(double[] a) { - int checkSum = 0; - - for (double e : a) { - checkSum ^= (int) e; // xor - } - return checkSum; - } - - private enum PrimitiveTypeArrayBuilder { - - RANDOM { - void build(int[] a, int m) { - for (int i = 0; i < a.length; i++) { - a[i] = ourRandom.nextInt(); - } - } - }, - - ASCENDING { - void build(int[] a, int m) { - for (int i = 0; i < a.length; i++) { - a[i] = m + i; - } - } - }, - - DESCENDING { - void build(int[] a, int m) { - for (int i = 0; i < a.length; i++) { - a[i] = a.length - m - i; - } - } - }, - - ALL_EQUAL { - void build(int[] a, int m) { - for (int i = 0; i < a.length; i++) { - a[i] = m; - } - } - }, - - SAW { - void build(int[] a, int m) { - int incCount = 1; - int decCount = a.length; - int i = 0; - int period = m; - m--; - - while (true) { - for (int k = 1; k <= period; k++) { - if (i >= a.length) { - return; - } - a[i++] = incCount++; - } - period += m; - - for (int k = 1; k <= period; k++) { - if (i >= a.length) { - return; - } - a[i++] = decCount--; - } - period += m; - } - } - }, - - REPEATED { - void build(int[] a, int m) { - for (int i = 0; i < a.length; i++) { - a[i] = i % m; - } - } - }, - - DUPLICATED { - void build(int[] a, int m) { - for (int i = 0; i < a.length; i++) { - a[i] = ourRandom.nextInt(m); - } - } - }, - - ORGAN_PIPES { - void build(int[] a, int m) { - int middle = a.length / (m + 1); - - for (int i = 0; i < middle; i++) { - a[i] = i; - } - for (int i = middle; i < a.length ; i++) { - a[i] = a.length - i - 1; - } - } - }, - - STAGGER { - void build(int[] a, int m) { - for (int i = 0; i < a.length; i++) { - a[i] = (i * m + i) % a.length; - } - } - }, - - PLATEAU { - void build(int[] a, int m) { - for (int i = 0; i < a.length; i++) { - a[i] = Math.min(i, m); - } - } - }, - - SHUFFLE { - void build(int[] a, int m) { - for (int i = 0; i < a.length; i++) { - a[i] = ourRandom.nextBoolean() ? (ourFirst += 2) : (ourSecond += 2); - } - } - }; - - abstract void build(int[] a, int m); - - static void reset() { - ourRandom = new Random(666); - ourFirst = 0; - ourSecond = 0; - } - - @Override - public String toString() { - String name = name(); - - for (int i = name.length(); i < 12; i++) { - name += " " ; - } - return name; - } - - private static int ourFirst; - private static int ourSecond; - private static Random ourRandom = new Random(666); - } - - private enum PrimitiveTypeConverter { - - INT { - Object convert(int[] a) { - return a; - } - }, - - LONG { - Object convert(int[] a) { - long[] b = new long[a.length]; - - for (int i = 0; i < a.length; i++) { - b[i] = (int) a[i]; - } - return b; - } - }, - - BYTE { - Object convert(int[] a) { - byte[] b = new byte[a.length]; - - for (int i = 0; i < a.length; i++) { - b[i] = (byte) a[i]; - } - return b; - } - }, - - SHORT { - Object convert(int[] a) { - short[] b = new short[a.length]; - - for (int i = 0; i < a.length; i++) { - b[i] = (short) a[i]; - } - return b; - } - }, - - CHAR { - Object convert(int[] a) { - char[] b = new char[a.length]; - - for (int i = 0; i < a.length; i++) { - b[i] = (char) a[i]; - } - return b; - } - }, - - FLOAT { - Object convert(int[] a) { - float[] b = new float[a.length]; - - for (int i = 0; i < a.length; i++) { - b[i] = (float) a[i]; - } - return b; - } - }, - - DOUBLE { - Object convert(int[] a) { - double[] b = new double[a.length]; - - for (int i = 0; i < a.length; i++) { - b[i] = (double) a[i]; - } - return b; - } - }; - - abstract Object convert(int[] a); - - public String toString() { - String name = name(); - - for (int i = name.length(); i < 9; i++) { - name += " " ; - } - return name; - } - } - - - /** - * java.util.Arrays#deepEquals(Object[], Object[]) - */ - public void test_deepEquals$Ljava_lang_ObjectLjava_lang_Object() { - int [] a1 = {1, 2, 3}; - short [] a2 = {0, 1}; - Object [] a3 = {new Integer(1), a2}; - int [] a4 = {6, 5, 4}; - - int [] b1 = {1, 2, 3}; - short [] b2 = {0, 1}; - Object [] b3 = {new Integer(1), b2}; - - Object a [] = {a1, a2, a3}; - Object b [] = {b1, b2, b3}; - - assertFalse(Arrays.equals(a, b)); - assertTrue(Arrays.deepEquals(a,b)); - - a[2] = a4; - - assertFalse(Arrays.deepEquals(a, b)); - } - - /** - * java.util.Arrays#deepHashCode(Object[]) - */ - public void test_deepHashCode$Ljava_lang_Object() { - int [] a1 = {1, 2, 3}; - short [] a2 = {0, 1}; - Object [] a3 = {new Integer(1), a2}; - - int [] b1 = {1, 2, 3}; - short [] b2 = {0, 1}; - Object [] b3 = {new Integer(1), b2}; - - Object a [] = {a1, a2, a3}; - Object b [] = {b1, b2, b3}; - - int deep_hash_a = Arrays.deepHashCode(a); - int deep_hash_b = Arrays.deepHashCode(b); - - assertEquals(deep_hash_a, deep_hash_b); - } - - /** - * java.util.Arrays#hashCode(boolean[] a) - */ - public void test_hashCode$LZ() { - int listHashCode; - int arrayHashCode; - - boolean [] boolArr = {true, false, false, true, false}; - List listOfBoolean = new LinkedList(); - for (int i = 0; i < boolArr.length; i++) { - listOfBoolean.add(new Boolean(boolArr[i])); - } - listHashCode = listOfBoolean.hashCode(); - arrayHashCode = Arrays.hashCode(boolArr); - assertEquals(listHashCode, arrayHashCode); - } - - /** - * java.util.Arrays#hashCode(int[] a) - */ - public void test_hashCode$LI() { - int listHashCode; - int arrayHashCode; - - int [] intArr = {10, 5, 134, 7, 19}; - List listOfInteger = new LinkedList(); - - for (int i = 0; i < intArr.length; i++) { - listOfInteger.add(new Integer(intArr[i])); - } - listHashCode = listOfInteger.hashCode(); - arrayHashCode = Arrays.hashCode(intArr); - assertEquals(listHashCode, arrayHashCode); - - int [] intArr2 = {10, 5, 134, 7, 19}; - assertEquals(Arrays.hashCode(intArr2), Arrays.hashCode(intArr)); - } - - /** - * java.util.Arrays#hashCode(char[] a) - */ - public void test_hashCode$LC() { - int listHashCode; - int arrayHashCode; - - char [] charArr = {'a', 'g', 'x', 'c', 'm'}; - List listOfCharacter = new LinkedList(); - for (int i = 0; i < charArr.length; i++) { - listOfCharacter.add(new Character(charArr[i])); - } - listHashCode = listOfCharacter.hashCode(); - arrayHashCode = Arrays.hashCode(charArr); - assertEquals(listHashCode, arrayHashCode); - } - - /** - * java.util.Arrays#hashCode(byte[] a) - */ - public void test_hashCode$LB() { - int listHashCode; - int arrayHashCode; - - byte [] byteArr = {5, 9, 7, 6, 17}; - List listOfByte = new LinkedList(); - for (int i = 0; i < byteArr.length; i++) { - listOfByte.add(new Byte(byteArr[i])); - } - listHashCode = listOfByte.hashCode(); - arrayHashCode = Arrays.hashCode(byteArr); - assertEquals(listHashCode, arrayHashCode); - } - - /** - * java.util.Arrays#hashCode(long[] a) - */ - public void test_hashCode$LJ() { - int listHashCode; - int arrayHashCode; - - long [] longArr = {67890234512l, 97587236923425l, 257421912912l, - 6754268100l, 5}; - List listOfLong = new LinkedList(); - for (int i = 0; i < longArr.length; i++) { - listOfLong.add(new Long(longArr[i])); - } - listHashCode = listOfLong.hashCode(); - arrayHashCode = Arrays.hashCode(longArr); - assertEquals(listHashCode, arrayHashCode); - } - - /** - * java.util.Arrays#hashCode(float[] a) - */ - public void test_hashCode$LF() { - int listHashCode; - int arrayHashCode; - - float [] floatArr = {0.13497f, 0.268934f, 12e-5f, -3e+2f, 10e-4f}; - List listOfFloat = new LinkedList(); - for (int i = 0; i < floatArr.length; i++) { - listOfFloat.add(new Float(floatArr[i])); - } - listHashCode = listOfFloat.hashCode(); - arrayHashCode = Arrays.hashCode(floatArr); - assertEquals(listHashCode, arrayHashCode); - - float [] floatArr2 = {0.13497f, 0.268934f, 12e-5f, -3e+2f, 10e-4f}; - assertEquals(Arrays.hashCode(floatArr2), Arrays.hashCode(floatArr)); - } - - /** - * java.util.Arrays#hashCode(double[] a) - */ - public void test_hashCode$LD() { - int listHashCode; - int arrayHashCode; - - double [] doubleArr = {0.134945657, 0.0038754, 11e-150, -30e-300, 10e-4}; - List listOfDouble = new LinkedList(); - for (int i = 0; i < doubleArr.length; i++) { - listOfDouble.add(new Double(doubleArr[i])); - } - listHashCode = listOfDouble.hashCode(); - arrayHashCode = Arrays.hashCode(doubleArr); - assertEquals(listHashCode, arrayHashCode); - } - - /** - * java.util.Arrays#hashCode(short[] a) - */ - public void test_hashCode$LS() { - int listHashCode; - int arrayHashCode; - - short [] shortArr = {35, 13, 45, 2, 91}; - List listOfShort = new LinkedList(); - for (int i = 0; i < shortArr.length; i++) { - listOfShort.add(new Short(shortArr[i])); - } - listHashCode = listOfShort.hashCode(); - arrayHashCode = Arrays.hashCode(shortArr); - assertEquals(listHashCode, arrayHashCode); - } - - /** - * java.util.Arrays#hashCode(Object[] a) - */ - public void test_hashCode$Ljava_lang_Object() { - int listHashCode; - int arrayHashCode; - - Object[] objectArr = {new Integer(1), new Float(10e-12f), null}; - List listOfObject= new LinkedList(); - for (int i = 0; i < objectArr.length; i++) { - listOfObject.add(objectArr[i]); - } - listHashCode = listOfObject.hashCode(); - arrayHashCode = Arrays.hashCode(objectArr); - assertEquals(listHashCode, arrayHashCode); - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - objArray = new Object[arraySize]; - for (int i = 0; i < objArray.length; i++) - objArray[i] = new Integer(i); - - booleanArray = new boolean[arraySize]; - byteArray = new byte[arraySize]; - charArray = new char[arraySize]; - doubleArray = new double[arraySize]; - floatArray = new float[arraySize]; - intArray = new int[arraySize]; - longArray = new long[arraySize]; - objectArray = new Object[arraySize]; - shortArray = new short[arraySize]; - - for (int counter = 0; counter < arraySize; counter++) { - byteArray[counter] = (byte) counter; - charArray[counter] = (char) (counter + 1); - doubleArray[counter] = counter; - floatArray[counter] = counter; - intArray[counter] = counter; - longArray[counter] = counter; - objectArray[counter] = objArray[counter]; - shortArray[counter] = (short) counter; - } - for (int counter = 0; counter < arraySize; counter += 2) { - booleanArray[counter] = false; - booleanArray[counter + 1] = true; - } - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - objArray = null; - booleanArray = null; - byteArray = null; - charArray = null; - doubleArray = null; - floatArray = null; - intArray = null; - longArray = null; - objectArray = null; - shortArray = null; - } -} diff --git a/luni/src/test/java/tests/api/java/util/BitSetTest.java b/luni/src/test/java/tests/api/java/util/BitSetTest.java deleted file mode 100644 index e1abc48..0000000 --- a/luni/src/test/java/tests/api/java/util/BitSetTest.java +++ /dev/null @@ -1,1279 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.BitSet; - -public class BitSetTest extends junit.framework.TestCase { - - BitSet eightbs; - - public void test_Constructor() { - BitSet bs = new BitSet(); - // Default size for a BitSet should be 64 elements; - assertEquals("Created BitSet of incorrect size", 64, bs.size()); - assertEquals("New BitSet had invalid string representation", "{}", bs.toString()); - } - - public void test_ConstructorI() { - BitSet bs = new BitSet(128); - // Default size for a BitSet should be 64 elements; - - assertEquals("Created BitSet of incorrect size", 128, bs.size()); - assertTrue("New BitSet had invalid string representation: " - + bs.toString(), bs.toString().equals("{}")); - - // All BitSets are created with elements of multiples of 64 - - bs = new BitSet(89); - assertEquals("Failed to round BitSet element size", 128, bs.size()); - - try { - bs = new BitSet(-9); - fail(); - } catch (NegativeArraySizeException expected) { - } - } - - public void test_clone() { - BitSet bs = (BitSet) eightbs.clone(); - assertTrue("Clone failed to return equal BitSet", eightbs.equals(bs)); - - } - - public void test_equalsLjava_lang_Object() { - BitSet bs; - - bs = (BitSet) eightbs.clone(); - assertTrue("Same BitSet returned false", eightbs.equals(eightbs)); - assertTrue("Identical BitSets returned false", eightbs.equals(bs)); - bs.clear(6); - assertTrue("Different BitSets returned true", !eightbs.equals(bs)); - // Grow the BitSet - bs = (BitSet) eightbs.clone(); - bs.set(128); - assertFalse(eightbs.equals(bs)); - bs.clear(128); - assertTrue(eightbs.equals(bs)); - } - - public void test_hashCode() { - BitSet bs = (BitSet) eightbs.clone(); - bs.clear(2); - bs.clear(6); - assertEquals("BitSet returns wrong hash value", 1129, bs.hashCode()); - bs.set(10); - bs.clear(3); - assertEquals("BitSet returns wrong hash value", 97, bs.hashCode()); - } - - public void test_clear() { - eightbs.clear(); - for (int i = 0; i < 8; i++) { - assertTrue("Clear didn't clear bit " + i, !eightbs.get(i)); - } - assertEquals("Test1: Wrong length", 0, eightbs.length()); - - BitSet bs = new BitSet(3400); - bs.set(0, bs.size() - 1); // ensure all bits are 1's - bs.set(bs.size() - 1); - bs.clear(); - assertEquals(0, bs.length()); - assertTrue(bs.isEmpty()); - assertEquals(0, bs.cardinality()); - } - - public void test_clearI() { - eightbs.clear(7); - assertFalse("Failed to clear bit", eightbs.get(7)); - - // Check to see all other bits are still set - for (int i = 0; i < 7; i++) - assertTrue("Clear cleared incorrect bits", eightbs.get(i)); - - eightbs.clear(165); - assertFalse("Failed to clear bit", eightbs.get(165)); - // Try out of range - try { - eightbs.clear(-1); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - - BitSet bs = new BitSet(0); - assertEquals("Test1: Wrong length,", 0, bs.length()); - assertEquals("Test1: Wrong size,", 0, bs.size()); - - bs.clear(0); - assertEquals("Test2: Wrong length,", 0, bs.length()); - assertEquals("Test2: Wrong size,", 0, bs.size()); - - bs.clear(60); - assertEquals("Test3: Wrong length,", 0, bs.length()); - assertEquals("Test3: Wrong size,", 0, bs.size()); - - bs.clear(120); - assertEquals("Test4: Wrong size,", 0, bs.size()); - assertEquals("Test4: Wrong length,", 0, bs.length()); - - bs.set(25); - assertEquals("Test5: Wrong size,", 64, bs.size()); - assertEquals("Test5: Wrong length,", 26, bs.length()); - - bs.clear(80); - assertEquals("Test6: Wrong size,", 64, bs.size()); - assertEquals("Test6: Wrong length,", 26, bs.length()); - - bs.clear(25); - assertEquals("Test7: Wrong size,", 64, bs.size()); - assertEquals("Test7: Wrong length,", 0, bs.length()); - } - - public void test_clearII() { - // Regression for HARMONY-98 - BitSet bitset = new BitSet(); - for (int i = 0; i < 20; i++) { - bitset.set(i); - } - bitset.clear(10, 10); - - // pos1 and pos2 are in the same bitset element - BitSet bs = new BitSet(16); - int initialSize = bs.size(); - assertEquals(64, initialSize); - bs.set(0, initialSize); - bs.clear(5); - bs.clear(15); - bs.clear(7, 11); - assertEquals("{0, 1, 2, 3, 4, 6, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, " + - "26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, " + - "46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63}", bs.toString()); - for (int i = initialSize; i < bs.size(); i++) { - assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); - } - - // pos1 and pos2 is in the same bitset element, boundry testing - bs = new BitSet(16); - initialSize = bs.size(); - bs.set(0, initialSize); - bs.clear(7, 64); - assertEquals("Failed to grow BitSet", 64, bs.size()); - for (int i = 0; i < 7; i++) { - assertTrue("Shouldn't have cleared bit " + i, bs.get(i)); - } - for (int i = 7; i < 64; i++) { - assertFalse("Failed to clear bit " + i, bs.get(i)); - } - for (int i = 64; i < bs.size(); i++) { - assertTrue("Shouldn't have flipped bit " + i, !bs.get(i)); - } - // more boundary testing - bs = new BitSet(32); - initialSize = bs.size(); - bs.set(0, initialSize); - bs.clear(0, 64); - for (int i = 0; i < 64; i++) { - assertFalse("Failed to clear bit " + i, bs.get(i)); - } - for (int i = 64; i < bs.size(); i++) { - assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); - } - - bs = new BitSet(32); - initialSize = bs.size(); - bs.set(0, initialSize); - bs.clear(0, 65); - for (int i = 0; i < 65; i++) { - assertFalse("Failed to clear bit " + i, bs.get(i)); - } - for (int i = 65; i < bs.size(); i++) { - assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); - } - - // pos1 and pos2 are in two sequential bitset elements - bs = new BitSet(128); - initialSize = bs.size(); - bs.set(0, initialSize); - bs.clear(7); - bs.clear(110); - bs.clear(9, 74); - for (int i = 0; i < 9; i++) { - if (i == 7) { - assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); - } else { - assertTrue("Shouldn't have cleared bit " + i, bs.get(i)); - } - } - for (int i = 9; i < 74; i++) { - assertFalse("Failed to clear bit " + i, bs.get(i)); - } - for (int i = 74; i < initialSize; i++) { - if (i == 110) { - assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); - } else { - assertTrue("Shouldn't have cleared bit " + i, bs.get(i)); - } - } - for (int i = initialSize; i < bs.size(); i++) { - assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); - } - - // pos1 and pos2 are in two non-sequential bitset elements - bs = new BitSet(256); - bs.set(0, 256); - bs.clear(7); - bs.clear(255); - bs.clear(9, 219); - for (int i = 0; i < 9; i++) { - if (i == 7) { - assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); - } else { - assertTrue("Shouldn't have cleared bit " + i, bs.get(i)); - } - } - - for (int i = 9; i < 219; i++) { - assertFalse("failed to clear bit " + i, bs.get(i)); - } - for (int i = 219; i < 255; i++) { - assertTrue("Shouldn't have cleared bit " + i, bs.get(i)); - } - for (int i = 255; i < bs.size(); i++) { - assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); - } - - // test illegal args - bs = new BitSet(10); - try { - bs.clear(-1, 3); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - - try { - bs.clear(2, -1); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - - bs.set(2, 4); - bs.clear(2, 2); - assertTrue("Bit got cleared incorrectly ", bs.get(2)); - - try { - bs.clear(4, 2); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - - bs = new BitSet(0); - assertEquals("Test1: Wrong length,", 0, bs.length()); - assertEquals("Test1: Wrong size,", 0, bs.size()); - - bs.clear(0, 2); - assertEquals("Test2: Wrong length,", 0, bs.length()); - assertEquals("Test2: Wrong size,", 0, bs.size()); - - bs.clear(60, 64); - assertEquals("Test3: Wrong length,", 0, bs.length()); - assertEquals("Test3: Wrong size,", 0, bs.size()); - - bs.clear(64, 120); - assertEquals("Test4: Wrong length,", 0, bs.length()); - assertEquals("Test4: Wrong size,", 0, bs.size()); - - bs.set(25); - assertEquals("Test5: Wrong length,", 26, bs.length()); - assertEquals("Test5: Wrong size,", 64, bs.size()); - - bs.clear(60, 64); - assertEquals("Test6: Wrong length,", 26, bs.length()); - assertEquals("Test6: Wrong size,", 64, bs.size()); - - bs.clear(64, 120); - assertEquals("Test7: Wrong size,", 64, bs.size()); - assertEquals("Test7: Wrong length,", 26, bs.length()); - - bs.clear(80); - assertEquals("Test8: Wrong size,", 64, bs.size()); - assertEquals("Test8: Wrong length,", 26, bs.length()); - - bs.clear(25); - assertEquals("Test9: Wrong size,", 64, bs.size()); - assertEquals("Test9: Wrong length,", 0, bs.length()); - } - - public void test_getI() { - BitSet bs = new BitSet(); - bs.set(8); - assertFalse("Get returned true for index out of range", eightbs.get(99)); - assertTrue("Get returned false for set value", eightbs.get(3)); - assertFalse("Get returned true for a non set value", bs.get(0)); - - try { - bs.get(-1); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - - bs = new BitSet(1); - assertFalse("Access greater than size", bs.get(64)); - - bs = new BitSet(); - bs.set(63); - assertTrue("Test highest bit", bs.get(63)); - - bs = new BitSet(0); - assertEquals("Test1: Wrong length,", 0, bs.length()); - assertEquals("Test1: Wrong size,", 0, bs.size()); - - bs.get(2); - assertEquals("Test2: Wrong length,", 0, bs.length()); - assertEquals("Test2: Wrong size,", 0, bs.size()); - - bs.get(70); - assertEquals("Test3: Wrong length,", 0, bs.length()); - assertEquals("Test3: Wrong size,", 0, bs.size()); - - } - - public void test_getII() { - BitSet bitset = new BitSet(30); - bitset.get(3, 3); - - BitSet bs, resultbs, correctbs; - bs = new BitSet(512); - bs.set(3, 9); - bs.set(10, 20); - bs.set(60, 75); - bs.set(121); - bs.set(130, 140); - - // pos1 and pos2 are in the same bitset element, at index0 - resultbs = bs.get(3, 6); - correctbs = new BitSet(3); - correctbs.set(0, 3); - assertEquals("Test1: Returned incorrect BitSet", correctbs, resultbs); - - // pos1 and pos2 are in the same bitset element, at index 1 - resultbs = bs.get(100, 125); - correctbs = new BitSet(25); - correctbs.set(21); - assertEquals("Test2: Returned incorrect BitSet", correctbs, resultbs); - - // pos1 in bitset element at index 0, and pos2 in bitset element at - // index 1 - resultbs = bs.get(15, 125); - correctbs = new BitSet(25); - correctbs.set(0, 5); - correctbs.set(45, 60); - correctbs.set(121 - 15); - assertEquals("Test3: Returned incorrect BitSet", correctbs, resultbs); - - // pos1 in bitset element at index 1, and pos2 in bitset element at - // index 2 - resultbs = bs.get(70, 145); - correctbs = new BitSet(75); - correctbs.set(0, 5); - correctbs.set(51); - correctbs.set(60, 70); - assertEquals("Test4: Returned incorrect BitSet", correctbs, resultbs); - - // pos1 in bitset element at index 0, and pos2 in bitset element at - // index 2 - resultbs = bs.get(5, 145); - correctbs = new BitSet(140); - correctbs.set(0, 4); - correctbs.set(5, 15); - correctbs.set(55, 70); - correctbs.set(116); - correctbs.set(125, 135); - assertEquals("Test5: Returned incorrect BitSet", correctbs, resultbs); - - // pos1 in bitset element at index 0, and pos2 in bitset element at - // index 3 - resultbs = bs.get(5, 250); - correctbs = new BitSet(200); - correctbs.set(0, 4); - correctbs.set(5, 15); - correctbs.set(55, 70); - correctbs.set(116); - correctbs.set(125, 135); - assertEquals("Test6: Returned incorrect BitSet", correctbs, resultbs); - - assertEquals("equality principle 1 ", bs.get(0, bs.size()), bs); - - // more tests - BitSet bs2 = new BitSet(129); - bs2.set(0, 20); - bs2.set(62, 65); - bs2.set(121, 123); - resultbs = bs2.get(1, 124); - correctbs = new BitSet(129); - correctbs.set(0, 19); - correctbs.set(61, 64); - correctbs.set(120, 122); - assertEquals("Test7: Returned incorrect BitSet", correctbs, resultbs); - - // equality principle with some boundary conditions - bs2 = new BitSet(128); - bs2.set(2, 20); - bs2.set(62); - bs2.set(121, 123); - bs2.set(127); - resultbs = bs2.get(0, bs2.size()); - assertEquals("equality principle 2 ", resultbs, bs2); - - bs2 = new BitSet(128); - bs2.set(2, 20); - bs2.set(62); - bs2.set(121, 123); - bs2.set(127); - bs2.flip(0, 128); - resultbs = bs2.get(0, bs.size()); - assertEquals("equality principle 3 ", resultbs, bs2); - - bs = new BitSet(0); - assertEquals("Test1: Wrong length,", 0, bs.length()); - assertEquals("Test1: Wrong size,", 0, bs.size()); - - bs.get(0, 2); - assertEquals("Test2: Wrong length,", 0, bs.length()); - assertEquals("Test2: Wrong size,", 0, bs.size()); - - bs.get(60, 64); - assertEquals("Test3: Wrong length,", 0, bs.length()); - assertEquals("Test3: Wrong size,", 0, bs.size()); - - bs.get(64, 120); - assertEquals("Test4: Wrong length,", 0, bs.length()); - assertEquals("Test4: Wrong size,", 0, bs.size()); - - bs.set(25); - assertEquals("Test5: Wrong length,", 26, bs.length()); - assertEquals("Test5: Wrong size,", 64, bs.size()); - - bs.get(60, 64); - assertEquals("Test6: Wrong length,", 26, bs.length()); - assertEquals("Test6: Wrong size,", 64, bs.size()); - - bs.get(64, 120); - assertEquals("Test7: Wrong size,", 64, bs.size()); - assertEquals("Test7: Wrong length,", 26, bs.length()); - - bs.get(80); - assertEquals("Test8: Wrong size,", 64, bs.size()); - assertEquals("Test8: Wrong length,", 26, bs.length()); - - bs.get(25); - assertEquals("Test9: Wrong size,", 64, bs.size()); - assertEquals("Test9: Wrong length,", 26, bs.length()); - - try { - bs2.get(-1, 0); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - - try { - bs2.get(bs2.size()/2, 0); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - - try { - bs2.get(bs2.size()/2, -1); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - } - - public void test_setI() { - BitSet bs = new BitSet(); - bs.set(8); - assertTrue("Failed to set bit", bs.get(8)); - - try { - bs.set(-1); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - - // Try setting a bit on a 64 boundary - bs.set(128); - assertEquals("Failed to grow BitSet", 192, bs.size()); - assertTrue("Failed to set bit", bs.get(128)); - - bs = new BitSet(64); - for (int i = bs.size(); --i >= 0;) { - bs.set(i); - assertTrue("Incorrectly set", bs.get(i)); - assertTrue("Incorrect length", bs.length() == (i + 1)); - for (int j = bs.size(); --j > i;) - assertTrue("Incorrectly set bit " + j, !bs.get(j)); - for (int j = i; --j >= 0;) - assertTrue("Incorrectly set bit " + j, !bs.get(j)); - bs.clear(i); - } - - bs = new BitSet(0); - assertTrue("Test1: Wrong length, " + bs.size(), bs.length() == 0); - bs.set(0); - assertTrue("Test2: Wrong length" + bs.size(), bs.length() == 1); - } - - public void test_setIZ() { - eightbs.set(5, false); - assertTrue("Should have set bit 5 to true", !eightbs.get(5)); - - eightbs.set(5, true); - assertTrue("Should have set bit 5 to false", eightbs.get(5)); - - try { - eightbs.set(-5, false); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - } - - public void test_setII() { - BitSet bitset = new BitSet(30); - bitset.set(29, 29); - - // pos1 and pos2 are in the same bitset element - BitSet bs = new BitSet(16); - bs.set(5); - bs.set(15); - bs.set(7, 11); - assertEquals("{5, 7, 8, 9, 10, 15}", bs.toString()); - for (int i = 16; i < bs.size(); i++) { - assertFalse("Shouldn't have set bit " + i, bs.get(i)); - } - - // pos1 and pos2 is in the same bitset element, boundry testing - bs = new BitSet(16); - bs.set(7, 64); - assertEquals("Failed to grow BitSet", 64, bs.size()); - for (int i = 0; i < 7; i++) { - assertFalse("Shouldn't have set bit " + i, bs.get(i)); - } - for (int i = 7; i < 64; i++) { - assertTrue("Failed to set bit " + i, bs.get(i)); - } - assertFalse("Shouldn't have set bit 64", bs.get(64)); - - // more boundary testing - bs = new BitSet(32); - bs.set(0, 64); - for (int i = 0; i < 64; i++) { - assertTrue("Failed to set bit " + i, bs.get(i)); - } - assertFalse("Shouldn't have set bit 64", bs.get(64)); - - bs = new BitSet(32); - bs.set(0, 65); - for (int i = 0; i < 65; i++) { - assertTrue("Failed to set bit " + i, bs.get(i)); - } - assertFalse("Shouldn't have set bit 65", bs.get(65)); - - // pos1 and pos2 are in two sequential bitset elements - bs = new BitSet(128); - bs.set(7); - bs.set(110); - bs.set(9, 74); - for (int i = 0; i < 9; i++) { - if (i == 7) { - assertTrue("Shouldn't have flipped bit " + i, bs.get(i)); - } else { - assertFalse("Shouldn't have set bit " + i, bs.get(i)); - } - } - for (int i = 9; i < 74; i++) { - assertTrue("Failed to set bit " + i, bs.get(i)); - } - for (int i = 74; i < bs.size(); i++) { - if (i == 110) { - assertTrue("Shouldn't have flipped bit " + i, bs.get(i)); - } else { - assertFalse("Shouldn't have set bit " + i, bs.get(i)); - } - } - - // pos1 and pos2 are in two non-sequential bitset elements - bs = new BitSet(256); - bs.set(7); - bs.set(255); - bs.set(9, 219); - for (int i = 0; i < 9; i++) { - if (i == 7) { - assertTrue("Shouldn't have set flipped " + i, bs.get(i)); - } else { - assertFalse("Shouldn't have set bit " + i, bs.get(i)); - } - } - - for (int i = 9; i < 219; i++) { - assertTrue("failed to set bit " + i, bs.get(i)); - } - - for (int i = 219; i < 255; i++) { - assertFalse("Shouldn't have set bit " + i, bs.get(i)); - } - - assertTrue("Shouldn't have flipped bit 255", bs.get(255)); - - // test illegal args - bs = new BitSet(10); - try { - bs.set(-1, 3); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - - try { - bs.set(2, -1); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - - bs.set(2, 2); - assertFalse("Bit got set incorrectly ", bs.get(2)); - - try { - bs.set(4, 2); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - } - - public void test_setIIZ() { - eightbs.set(3, 6, false); - assertTrue("Should have set bits 3, 4, and 5 to false", !eightbs.get(3) - && !eightbs.get(4) && !eightbs.get(5)); - - eightbs.set(3, 6, true); - assertTrue("Should have set bits 3, 4, and 5 to true", eightbs.get(3) - && eightbs.get(4) && eightbs.get(5)); - - try { - eightbs.set(-3, 6, false); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - - try { - eightbs.set(3, -6, false); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - - try { - eightbs.set(6, 3, false); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - } - - public void test_flipI() { - BitSet bs = new BitSet(); - bs.clear(8); - bs.clear(9); - bs.set(10); - bs.flip(9); - assertFalse("Failed to flip bit", bs.get(8)); - assertTrue("Failed to flip bit", bs.get(9)); - assertTrue("Failed to flip bit", bs.get(10)); - - bs.set(8); - bs.set(9); - bs.clear(10); - bs.flip(9); - assertTrue("Failed to flip bit", bs.get(8)); - assertFalse("Failed to flip bit", bs.get(9)); - assertFalse("Failed to flip bit", bs.get(10)); - - try { - bs.flip(-1); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - - // Try setting a bit on a 64 boundary - bs.flip(128); - assertEquals("Failed to grow BitSet", 192, bs.size()); - assertTrue("Failed to flip bit", bs.get(128)); - - bs = new BitSet(64); - for (int i = bs.size(); --i >= 0;) { - bs.flip(i); - assertTrue("Test1: Incorrectly flipped bit" + i, bs.get(i)); - assertEquals("Incorrect length", i+1, bs.length()); - for (int j = bs.size(); --j > i;) { - assertTrue("Test2: Incorrectly flipped bit" + j, !bs.get(j)); - } - for (int j = i; --j >= 0;) { - assertTrue("Test3: Incorrectly flipped bit" + j, !bs.get(j)); - } - bs.flip(i); - } - - BitSet bs0 = new BitSet(0); - assertEquals("Test1: Wrong size", 0, bs0.size()); - assertEquals("Test1: Wrong length", 0, bs0.length()); - - bs0.flip(0); - assertEquals("Test2: Wrong size", 64, bs0.size()); - assertEquals("Test2: Wrong length", 1, bs0.length()); - - bs0.flip(63); - assertEquals("Test3: Wrong size", 64, bs0.size()); - assertEquals("Test3: Wrong length", 64, bs0.length()); - - eightbs.flip(7); - assertTrue("Failed to flip bit 7", !eightbs.get(7)); - - // Check to see all other bits are still set - for (int i = 0; i < 7; i++) { - assertTrue("Flip flipped incorrect bits", eightbs.get(i)); - } - - eightbs.flip(127); - assertTrue("Failed to flip bit 127", eightbs.get(127)); - - eightbs.flip(127); - assertTrue("Failed to flip bit 127", !eightbs.get(127)); - } - - public void test_flipII() { - BitSet bitset = new BitSet(); - for (int i = 0; i < 20; i++) { - bitset.set(i); - } - bitset.flip(10, 10); - - // pos1 and pos2 are in the same bitset element - BitSet bs = new BitSet(16); - bs.set(7); - bs.set(10); - bs.flip(7, 11); - for (int i = 0; i < 7; i++) { - assertTrue("Shouldn't have flipped bit " + i, !bs.get(i)); - } - assertFalse("Failed to flip bit 7", bs.get(7)); - assertTrue("Failed to flip bit 8", bs.get(8)); - assertTrue("Failed to flip bit 9", bs.get(9)); - assertFalse("Failed to flip bit 10", bs.get(10)); - for (int i = 11; i < bs.size(); i++) { - assertTrue("Shouldn't have flipped bit " + i, !bs.get(i)); - } - - // pos1 and pos2 is in the same bitset element, boundry testing - bs = new BitSet(16); - bs.set(7); - bs.set(10); - bs.flip(7, 64); - assertEquals("Failed to grow BitSet", 64, bs.size()); - for (int i = 0; i < 7; i++) { - assertTrue("Shouldn't have flipped bit " + i, !bs.get(i)); - } - assertFalse("Failed to flip bit 7", bs.get(7)); - assertTrue("Failed to flip bit 8", bs.get(8)); - assertTrue("Failed to flip bit 9", bs.get(9)); - assertFalse("Failed to flip bit 10", bs.get(10)); - for (int i = 11; i < 64; i++) { - assertTrue("failed to flip bit " + i, bs.get(i)); - } - assertFalse("Shouldn't have flipped bit 64", bs.get(64)); - - // more boundary testing - bs = new BitSet(32); - bs.flip(0, 64); - for (int i = 0; i < 64; i++) { - assertTrue("Failed to flip bit " + i, bs.get(i)); - } - assertFalse("Shouldn't have flipped bit 64", bs.get(64)); - - bs = new BitSet(32); - bs.flip(0, 65); - for (int i = 0; i < 65; i++) { - assertTrue("Failed to flip bit " + i, bs.get(i)); - } - assertFalse("Shouldn't have flipped bit 65", bs.get(65)); - - // pos1 and pos2 are in two sequential bitset elements - bs = new BitSet(128); - bs.set(7); - bs.set(10); - bs.set(72); - bs.set(110); - bs.flip(9, 74); - for (int i = 0; i < 7; i++) { - assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); - } - assertTrue("Shouldn't have flipped bit 7", bs.get(7)); - assertFalse("Shouldn't have flipped bit 8", bs.get(8)); - assertTrue("Failed to flip bit 9", bs.get(9)); - assertFalse("Failed to flip bit 10", bs.get(10)); - for (int i = 11; i < 72; i++) { - assertTrue("failed to flip bit " + i, bs.get(i)); - } - assertFalse("Failed to flip bit 72", bs.get(72)); - assertTrue("Failed to flip bit 73", bs.get(73)); - for (int i = 74; i < 110; i++) { - assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); - } - assertTrue("Shouldn't have flipped bit 110", bs.get(110)); - for (int i = 111; i < bs.size(); i++) { - assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); - } - - // pos1 and pos2 are in two non-sequential bitset elements - bs = new BitSet(256); - bs.set(7); - bs.set(10); - bs.set(72); - bs.set(110); - bs.set(181); - bs.set(220); - bs.flip(9, 219); - for (int i = 0; i < 7; i++) { - assertFalse("Shouldn't have flipped bit " + i, bs.get(i)); - } - assertTrue("Shouldn't have flipped bit 7", bs.get(7)); - assertFalse("Shouldn't have flipped bit 8", bs.get(8)); - assertTrue("Failed to flip bit 9", bs.get(9)); - assertFalse("Failed to flip bit 10", bs.get(10)); - for (int i = 11; i < 72; i++) { - assertTrue("failed to flip bit " + i, bs.get(i)); - } - assertFalse("Failed to flip bit 72", bs.get(72)); - for (int i = 73; i < 110; i++) { - assertTrue("failed to flip bit " + i, bs.get(i)); - } - assertFalse("Failed to flip bit 110", bs.get(110)); - for (int i = 111; i < 181; i++) { - assertTrue("failed to flip bit " + i, bs.get(i)); - } - assertFalse("Failed to flip bit 181", bs.get(181)); - for (int i = 182; i < 219; i++) { - assertTrue("failed to flip bit " + i, bs.get(i)); - } - assertFalse("Shouldn't have flipped bit 219", bs.get(219)); - assertTrue("Shouldn't have flipped bit 220", bs.get(220)); - for (int i = 221; i < bs.size(); i++) { - assertTrue("Shouldn't have flipped bit " + i, !bs.get(i)); - } - - // test illegal args - bs = new BitSet(10); - try { - bs.flip(-1, 3); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - - try { - bs.flip(2, -1); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - - try { - bs.flip(4, 2); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - } - - public void test_111478() throws Exception { - // BitSet shouldn't be modified by any of the operations below, - // since the affected bits for these methods are defined as inclusive of - // pos1, exclusive of pos2. - eightbs.flip(0, 0); - assertTrue("Bit got flipped incorrectly ", eightbs.get(0)); - - BitSet bsnew = eightbs.get(2, 2); - assertEquals(0, bsnew.cardinality()); - - eightbs.set(10, 10); - assertTrue("Bit got set incorrectly ", !eightbs.get(10)); - - eightbs.clear(3, 3); - assertTrue("Bit cleared incorrectly ", eightbs.get(3)); - } - - public void test_intersectsLjava_util_BitSet() { - BitSet bs = new BitSet(500); - bs.set(5); - bs.set(63); - bs.set(64); - bs.set(71, 110); - bs.set(127, 130); - bs.set(192); - bs.set(450); - - BitSet bs2 = new BitSet(8); - assertFalse("Test1: intersects() returned incorrect value", bs.intersects(bs2)); - assertFalse("Test1: intersects() returned incorrect value", bs2.intersects(bs)); - - bs2.set(4); - assertFalse("Test2: intersects() returned incorrect value", bs.intersects(bs2)); - assertFalse("Test2: intersects() returned incorrect value", bs2.intersects(bs)); - - bs2.clear(); - bs2.set(5); - assertTrue("Test3: intersects() returned incorrect value", bs.intersects(bs2)); - assertTrue("Test3: intersects() returned incorrect value", bs2.intersects(bs)); - - bs2.clear(); - bs2.set(63); - assertTrue("Test4: intersects() returned incorrect value", bs.intersects(bs2)); - assertTrue("Test4: intersects() returned incorrect value", bs2.intersects(bs)); - - bs2.clear(); - bs2.set(80); - assertTrue("Test5: intersects() returned incorrect value", bs.intersects(bs2)); - assertTrue("Test5: intersects() returned incorrect value", bs2.intersects(bs)); - - bs2.clear(); - bs2.set(127); - assertTrue("Test6: intersects() returned incorrect value", bs.intersects(bs2)); - assertTrue("Test6: intersects() returned incorrect value", bs2.intersects(bs)); - - bs2.clear(); - bs2.set(192); - assertTrue("Test7: intersects() returned incorrect value", bs.intersects(bs2)); - assertTrue("Test7: intersects() returned incorrect value", bs2.intersects(bs)); - - bs2.clear(); - bs2.set(450); - assertTrue("Test8: intersects() returned incorrect value", bs.intersects(bs2)); - assertTrue("Test8: intersects() returned incorrect value", bs2.intersects(bs)); - - bs2.clear(); - bs2.set(500); - assertFalse("Test9: intersects() returned incorrect value", bs.intersects(bs2)); - assertFalse("Test9: intersects() returned incorrect value", bs2.intersects(bs)); - } - - public void test_andLjava_util_BitSet() { - BitSet bs = new BitSet(128); - // Initialize the bottom half of the BitSet - for (int i = 64; i < 128; i++) { - bs.set(i); - } - eightbs.and(bs); - assertTrue("AND failed to clear bits", !eightbs.equals(bs)); - eightbs.set(3); - bs.set(3); - eightbs.and(bs); - assertTrue("AND failed to maintain set bits", bs.get(3)); - bs.and(eightbs); - for (int i = 64; i < 128; i++) { - assertTrue("Failed to clear extra bits in the receiver BitSet", !bs.get(i)); - } - } - - public void test_andNotLjava_util_BitSet() { - BitSet bs = (BitSet) eightbs.clone(); - bs.clear(5); - BitSet bs2 = new BitSet(); - bs2.set(2); - bs2.set(3); - bs.andNot(bs2); - assertEquals("Incorrect bitset after andNot", - "{0, 1, 4, 6, 7}", bs.toString()); - - bs = new BitSet(0); - bs.andNot(bs2); - assertEquals("Incorrect size", 0, bs.size()); - } - - public void test_orLjava_util_BitSet() { - BitSet bs = new BitSet(128); - bs.or(eightbs); - for (int i = 0; i < 8; i++) { - assertTrue("OR failed to set bits", bs.get(i)); - } - bs = new BitSet(0); - bs.or(eightbs); - for (int i = 0; i < 8; i++) { - assertTrue("OR(0) failed to set bits", bs.get(i)); - } - eightbs.clear(5); - bs = new BitSet(128); - bs.or(eightbs); - assertTrue("OR set a bit which should be off", !bs.get(5)); - } - - public void test_xorLjava_util_BitSet() { - BitSet bs = (BitSet) eightbs.clone(); - bs.xor(eightbs); - for (int i = 0; i < 8; i++) { - assertTrue("XOR failed to clear bit " + i + bs, !bs.get(i)); - } - bs.xor(eightbs); - for (int i = 0; i < 8; i++) { - assertTrue("XOR failed to set bit " + i + bs, bs.get(i)); - } - bs = new BitSet(0); - bs.xor(eightbs); - for (int i = 0; i < 8; i++) { - assertTrue("XOR(0) failed to set bit " + i + bs, bs.get(i)); - } - bs = new BitSet(); - bs.set(63); - assertEquals("{63}", bs.toString()); - } - - public void test_size() { - assertEquals("Returned incorrect size", 64, eightbs.size()); - eightbs.set(129); - assertTrue("Returned incorrect size", eightbs.size() >= 129); - - } - - public void test_toString() { - assertEquals("Returned incorrect string representation", "{0, 1, 2, 3, 4, 5, 6, 7}", eightbs.toString()); - eightbs.clear(2); - assertEquals("Returned incorrect string representation", "{0, 1, 3, 4, 5, 6, 7}", eightbs.toString()); - } - - public void test_length() { - BitSet bs = new BitSet(); - assertEquals(bs.toString(), 0, bs.length()); - bs.set(5); - assertEquals(bs.toString(), 6, bs.length()); - bs.set(10); - assertEquals(bs.toString(), 11, bs.length()); - bs.set(432); - assertEquals(bs.toString(), 433, bs.length()); - bs.set(300); - assertEquals(bs.toString(), 433, bs.length()); - } - - public void test_nextSetBitI() { - BitSet bs = new BitSet(500); - bs.set(5); - bs.set(32); - bs.set(63); - bs.set(64); - bs.set(71, 110); - bs.set(127, 130); - bs.set(193); - bs.set(450); - try { - bs.nextSetBit(-1); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - assertEquals(5, bs.nextSetBit(0)); - assertEquals(5, bs.nextSetBit(5)); - assertEquals(32, bs.nextSetBit(6)); - assertEquals(32, bs.nextSetBit(32)); - assertEquals(63, bs.nextSetBit(33)); - - // boundary tests - assertEquals(63, bs.nextSetBit(63)); - assertEquals(64, bs.nextSetBit(64)); - - // at bitset element 1 - assertEquals(71, bs.nextSetBit(65)); - assertEquals(71, bs.nextSetBit(71)); - assertEquals(72, bs.nextSetBit(72)); - assertEquals(127, bs.nextSetBit(110)); - - // boundary tests - assertEquals(127, bs.nextSetBit(127)); - assertEquals(128, bs.nextSetBit(128)); - - // at bitset element 2 - assertEquals(193, bs.nextSetBit(130)); - - assertEquals(193, bs.nextSetBit(191)); - assertEquals(193, bs.nextSetBit(192)); - assertEquals(193, bs.nextSetBit(193)); - assertEquals(450, bs.nextSetBit(194)); - assertEquals(450, bs.nextSetBit(255)); - assertEquals(450, bs.nextSetBit(256)); - assertEquals(450, bs.nextSetBit(450)); - - assertEquals(-1, bs.nextSetBit(451)); - assertEquals(-1, bs.nextSetBit(511)); - assertEquals(-1, bs.nextSetBit(512)); - assertEquals(-1, bs.nextSetBit(800)); - } - - public void test_nextClearBitI() { - BitSet bs = new BitSet(500); - // ensure all the bits from 0 to bs.size() - 1 are set to true - bs.set(0, bs.size() - 1); - bs.set(bs.size() - 1); - bs.clear(5); - bs.clear(32); - bs.clear(63); - bs.clear(64); - bs.clear(71, 110); - bs.clear(127, 130); - bs.clear(193); - bs.clear(450); - try { - bs.nextClearBit(-1); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - assertEquals(5, bs.nextClearBit(0)); - assertEquals(5, bs.nextClearBit(5)); - assertEquals(32, bs.nextClearBit(6)); - assertEquals(32, bs.nextClearBit(32)); - assertEquals(63, bs.nextClearBit(33)); - - // boundary tests - assertEquals(63, bs.nextClearBit(63)); - assertEquals(64, bs.nextClearBit(64)); - - // at bitset element 1 - assertEquals(71, bs.nextClearBit(65)); - assertEquals(71, bs.nextClearBit(71)); - assertEquals(72, bs.nextClearBit(72)); - assertEquals(127, bs.nextClearBit(110)); - - // boundary tests - assertEquals(127, bs.nextClearBit(127)); - assertEquals(128, bs.nextClearBit(128)); - - // at bitset element 2 - assertEquals(193, bs.nextClearBit(130)); - assertEquals(193, bs.nextClearBit(191)); - - assertEquals(193, bs.nextClearBit(192)); - assertEquals(193, bs.nextClearBit(193)); - assertEquals(450, bs.nextClearBit(194)); - assertEquals(450, bs.nextClearBit(255)); - assertEquals(450, bs.nextClearBit(256)); - assertEquals(450, bs.nextClearBit(450)); - - // bitset has 1 still the end of bs.size() -1, but calling nextClearBit - // with any index value after the last true bit should return bs.size() - assertEquals(512, bs.nextClearBit(451)); - assertEquals(512, bs.nextClearBit(511)); - assertEquals(512, bs.nextClearBit(512)); - - // if the index is larger than bs.size(), nextClearBit should return index - assertEquals(513, bs.nextClearBit(513)); - assertEquals(800, bs.nextClearBit(800)); - - bs.clear(); - assertEquals(0, bs.nextClearBit(0)); - assertEquals(3, bs.nextClearBit(3)); - assertEquals(64, bs.nextClearBit(64)); - assertEquals(128, bs.nextClearBit(128)); - } - - // http://code.google.com/p/android/issues/detail?id=31036 - public void test_31036_clear() { - BitSet bs = new BitSet(500); - for (int i = 0; i < 500; ++i) { - int nextClear = bs.nextClearBit(0); - assertEquals(i, nextClear); - bs.set(i); - } - } - - // http://code.google.com/p/android/issues/detail?id=31036 - public void test_31036_set() { - BitSet bs = new BitSet(500); - bs.set(0, 511); - for (int i = 0; i < 500; ++i) { - int nextSet = bs.nextSetBit(0); - assertEquals(i, nextSet); - bs.clear(i); - } - } - - public void test_isEmpty() { - BitSet bs = new BitSet(500); - assertTrue("Test: isEmpty() returned wrong value", bs.isEmpty()); - - // at bitset element 0 - bs.set(3); - assertFalse("Test0: isEmpty() returned wrong value", bs.isEmpty()); - - // at bitset element 1 - bs.clear(); - bs.set(12); - assertFalse("Test1: isEmpty() returned wrong value", bs.isEmpty()); - - // at bitset element 2 - bs.clear(); - bs.set(128); - assertFalse("Test2: isEmpty() returned wrong value", bs.isEmpty()); - - // boundary testing - bs.clear(); - bs.set(459); - assertFalse("Test3: isEmpty() returned wrong value", bs.isEmpty()); - - bs.clear(); - bs.set(511); - assertFalse("Test4: isEmpty() returned wrong value", bs.isEmpty()); - } - - public void test_cardinality() { - BitSet bs = new BitSet(500); - bs.set(5); - bs.set(32); - bs.set(63); - bs.set(64); - assertEquals(bs.toString(), 4, bs.cardinality()); - bs.set(71, 110); - bs.set(127, 130); - bs.set(193); - bs.set(450); - assertEquals(bs.toString(), 48, bs.cardinality()); - - bs.flip(0, 500); - assertEquals("cardinality() returned wrong value", 452, bs - .cardinality()); - - bs.clear(); - assertEquals("cardinality() returned wrong value", 0, bs.cardinality()); - - bs.set(0, 500); - assertEquals("cardinality() returned wrong value", 500, bs - .cardinality()); - } - - private static void printBitset(BitSet bs) { - System.out.println(); - for (int i = bs.size() - 1; i >= 0; i--) { - if (bs.get(i)) - System.out.print(1); - else - System.out.print(0); - } - } - - protected void setUp() { - eightbs = new BitSet(); - for (int i = 0; i < 8; i++) { - eightbs.set(i); - } - } -} diff --git a/luni/src/test/java/tests/api/java/util/CalendarTest.java b/luni/src/test/java/tests/api/java/util/CalendarTest.java deleted file mode 100644 index 54524ad..0000000 --- a/luni/src/test/java/tests/api/java/util/CalendarTest.java +++ /dev/null @@ -1,1099 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.text.DateFormatSymbols; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.TimeZone; - -import org.apache.harmony.testframework.serialization.SerializationTest; - -public class CalendarTest extends junit.framework.TestCase { - - Locale defaultLocale; - - /** - * java.util.Calendar#set(int, int) - */ - public void test_setII() { - // Test for correct result defined by the last set field - Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST")); - - cal.clear(); - cal.set(Calendar.YEAR, 2002); - assertTrue("Incorrect result 0: " + cal.getTime().getTime(), cal - .getTime().getTime() == 1009861200000L); - - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.MONTH, Calendar.MARCH); - assertTrue("Incorrect result 0a: " + cal.getTime(), cal.getTime() - .getTime() == 1014958800000L); - - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.DATE, 24); - assertTrue("Incorrect result 0b: " + cal.getTime(), cal.getTime() - .getTime() == 1011848400000L); - - cal.set(Calendar.MONTH, Calendar.OCTOBER); - cal.set(Calendar.DATE, 31); - cal.set(Calendar.MONTH, Calendar.NOVEMBER); - cal.set(Calendar.DATE, 26); - assertTrue("Incorrect month: " + cal.get(Calendar.MONTH), cal - .get(Calendar.MONTH) == Calendar.NOVEMBER); - - int dow = cal.get(Calendar.DAY_OF_WEEK); - cal.set(Calendar.DATE, 27); - assertTrue("Incorrect DAY_OF_WEEK: " + cal.get(Calendar.DAY_OF_WEEK) - + " expected: " + dow, cal.get(Calendar.DAY_OF_WEEK) != dow); - - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); - assertTrue("Incorrect result 0c1: " + cal.getTime().getTime(), cal - .getTime().getTime() == 1010379600000L); - - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); - assertTrue("Incorrect result 0c2: " + cal.getTime().getTime(), cal - .getTime().getTime() == 1009861200000L); - - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY); - assertTrue("Incorrect result 0c3: " + cal.getTime(), cal.getTime() - .getTime() == 1010034000000L); - - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.WEEK_OF_MONTH, 2); - assertTrue("Incorrect result 0d: " + cal.getTime(), cal.getTime() - .getTime() == 1010293200000L); - - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 2); - assertTrue("Incorrect result 0e: " + cal.getTime(), cal.getTime() - .getTime() == 1010898000000L); - - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.WEEK_OF_YEAR, 11); - assertTrue("Incorrect result 0f: " + cal.getTime(), cal.getTime() - .getTime() == 1015736400000L); - - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.DATE, 24); - cal.set(Calendar.WEEK_OF_YEAR, 11); - assertTrue("Incorrect result 0g: " + cal.getTime(), cal.getTime() - .getTime() == 1011848400000L); - - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.get(Calendar.WEEK_OF_YEAR); // Force fields to compute - cal.set(Calendar.WEEK_OF_YEAR, 11); - assertTrue("Incorrect result 0h: " + cal.getTime(), cal.getTime() - .getTime() == 1015909200000L); - - // WEEK_OF_YEAR has priority over MONTH/DATE - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.DAY_OF_YEAR, 170); - cal.set(Calendar.WEEK_OF_YEAR, 11); - cal.set(Calendar.MONTH, Calendar.JANUARY); - cal.set(Calendar.DATE, 5); - cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); - assertTrue("Incorrect result 1: " + cal.getTime(), cal.getTime() - .getTime() == 1015822800000L); - - // WEEK_OF_YEAR has priority over MONTH/DATE - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.WEEK_OF_YEAR, 11); - cal.set(Calendar.MONTH, Calendar.JANUARY); - cal.set(Calendar.DATE, 5); - cal.set(Calendar.DAY_OF_YEAR, 170); - cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); - assertTrue("Incorrect result 1a: " + cal.getTime(), cal.getTime() - .getTime() == 1015822800000L); - - // DAY_OF_WEEK has no effect when other fields not set - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.MONTH, Calendar.MARCH); - cal.set(Calendar.DATE, 11); - cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); - assertTrue("Incorrect result 1b: " + cal.getTime(), cal.getTime() - .getTime() == 1015822800000L); - // Regression for HARMONY-4384 - // Set DAY_OF_WEEK without DATE - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.MONTH, Calendar.MARCH); - cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); - assertEquals("Incorrect result 1b: " + cal.getTime(), 1015304400000L, cal.getTime() - .getTime()); - - - // WEEK_OF_MONTH has priority - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.WEEK_OF_YEAR, 12); - cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1); - cal.set(Calendar.WEEK_OF_MONTH, 3); - cal.set(Calendar.MONTH, Calendar.MARCH); - cal.set(Calendar.DATE, 5); - cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); - assertTrue("Incorrect result 2: " + cal.getTime(), cal.getTime() - .getTime() == 1015822800000L); - - // DAY_OF_WEEK_IN_MONTH has priority over WEEK_OF_YEAR - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.WEEK_OF_YEAR, 12); - cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 2); - cal.set(Calendar.MONTH, Calendar.MARCH); - cal.set(Calendar.DATE, 5); - cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); - assertTrue("Incorrect result 3: " + cal.getTime(), cal.getTime() - .getTime() == 1015822800000L); - - // WEEK_OF_MONTH has priority, MONTH not set - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.WEEK_OF_YEAR, 12); - cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1); - cal.set(Calendar.WEEK_OF_MONTH, 3); - cal.set(Calendar.DATE, 25); - cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); - assertTrue("Incorrect result 4: " + cal.getTime(), cal.getTime() - .getTime() == 1010984400000L); - - // WEEK_OF_YEAR has priority when MONTH set last and DAY_OF_WEEK set - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.WEEK_OF_YEAR, 11); - cal.set(Calendar.DATE, 25); - cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); - cal.set(Calendar.MONTH, Calendar.JANUARY); - assertTrue("Incorrect result 5: " + cal.getTime(), cal.getTime() - .getTime() == 1015822800000L); - - // Use MONTH/DATE when WEEK_OF_YEAR set but not DAY_OF_WEEK - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.WEEK_OF_YEAR, 12); - cal.set(Calendar.DATE, 11); - cal.set(Calendar.MONTH, Calendar.MARCH); - assertTrue("Incorrect result 5a: " + cal.getTime(), cal.getTime() - .getTime() == 1015822800000L); - - // Use MONTH/DATE when DAY_OF_WEEK is not set - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.WEEK_OF_YEAR, 12); - cal.set(Calendar.DATE, 11); - cal.set(Calendar.WEEK_OF_MONTH, 1); - cal.set(Calendar.MONTH, Calendar.MARCH); - assertTrue("Incorrect result 5b: " + cal.getTime(), cal.getTime() - .getTime() == 1015822800000L); - - // WEEK_OF_MONTH has priority - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.WEEK_OF_YEAR, 12); - cal.set(Calendar.DATE, 5); - cal.set(Calendar.WEEK_OF_MONTH, 3); - cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); - cal.set(Calendar.MONTH, Calendar.MARCH); - assertTrue("Incorrect result 5c: " + cal.getTime(), cal.getTime() - .getTime() == 1015822800000L); - - // DATE has priority when set last - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.WEEK_OF_YEAR, 12); - cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); - cal.set(Calendar.MONTH, Calendar.MARCH); - cal.set(Calendar.DATE, 11); - assertTrue("Incorrect result 6: " + cal.getTime(), cal.getTime() - .getTime() == 1015822800000L); - - // DATE has priority when set last, MONTH not set - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.WEEK_OF_YEAR, 12); - cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); - cal.set(Calendar.DATE, 14); - assertTrue("Incorrect result 7: " + cal.getTime(), cal.getTime() - .getTime() == 1010984400000L); - - // DAY_OF_YEAR has priority when MONTH set last and DATE not set - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.DAY_OF_YEAR, 70); - cal.set(Calendar.MONTH, Calendar.JANUARY); - assertTrue("Incorrect result 8: " + cal.getTime(), cal.getTime() - .getTime() == 1015822800000L); - - // DAY/MONTH has priority when DATE set after DAY_OF_YEAR - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.DAY_OF_YEAR, 170); - cal.set(Calendar.DATE, 11); - cal.set(Calendar.MONTH, Calendar.MARCH); - assertTrue("Incorrect result 8a: " + cal.getTime(), cal.getTime() - .getTime() == 1015822800000L); - - // DAY_OF_YEAR has priority when set after DATE - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.DATE, 15); - cal.set(Calendar.DAY_OF_YEAR, 70); - cal.set(Calendar.MONTH, Calendar.JANUARY); - assertTrue("Incorrect result 8b: " + cal.getTime(), cal.getTime() - .getTime() == 1015822800000L); - - // DATE has priority when set last - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.DAY_OF_YEAR, 70); - cal.set(Calendar.DATE, 14); - assertTrue("Incorrect result 9: " + cal.getTime(), cal.getTime() - .getTime() == 1010984400000L); - - // DATE has priority when set last - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.WEEK_OF_YEAR, 15); - cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY); - cal.set(Calendar.DATE, 14); - assertTrue("Incorrect result 9a: " + cal.getTime(), cal.getTime() - .getTime() == 1010984400000L); - - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); - cal.set(Calendar.DATE, 14); - cal.set(Calendar.WEEK_OF_YEAR, 11); - assertTrue("Incorrect result 9b: " + cal.getTime(), cal.getTime() - .getTime() == 1015822800000L); - - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.DATE, 14); - cal.set(Calendar.WEEK_OF_YEAR, 11); - assertTrue("Incorrect result 9c: " + cal.getTime(), cal.getTime() - .getTime() == 1010984400000L); - - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.WEEK_OF_MONTH, 1); - cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY); - cal.set(Calendar.MONTH, Calendar.MARCH); - cal.set(Calendar.DATE, 11); - assertTrue("Incorrect result 9d: " + cal.getTime(), cal.getTime() - .getTime() == 1015822800000L); - - // DAY_OF_YEAR has priority when DAY_OF_MONTH set last and other fields - // not set - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.DAY_OF_YEAR, 70); - cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); - assertTrue("Incorrect result 10: " + cal.getTime(), cal.getTime() - .getTime() == 1015822800000L); - - // MONTH/DATE has priority when DAY_OF_WEEK_IN_MONTH set last but - // DAY_OF_WEEK not set - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.DATE, 11); - cal.set(Calendar.MONTH, Calendar.MARCH); - cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1); - assertTrue("Incorrect result 11: " + cal.getTime(), cal.getTime() - .getTime() == 1015822800000L); - - // MONTH/DATE has priority when WEEK_OF_YEAR set last but DAY_OF_WEEK - // not set - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.DATE, 11); - cal.set(Calendar.MONTH, Calendar.MARCH); - cal.set(Calendar.WEEK_OF_YEAR, 15); - assertTrue("Incorrect result 12: " + cal.getTime(), cal.getTime() - .getTime() == 1015822800000L); - - // MONTH/DATE has priority when WEEK_OF_MONTH set last but DAY_OF_WEEK - // not set - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.DATE, 11); - cal.set(Calendar.MONTH, Calendar.MARCH); - cal.set(Calendar.WEEK_OF_MONTH, 1); - assertTrue("Incorrect result 13: " + cal.getTime(), cal.getTime() - .getTime() == 1015822800000L); - - // Ensure last date field set is reset after computing - cal.clear(); - cal.set(Calendar.YEAR, 2002); - cal.set(Calendar.DAY_OF_YEAR, 111); - cal.get(Calendar.YEAR); - cal.set(Calendar.MONTH, Calendar.MARCH); - cal.set(Calendar.AM_PM, Calendar.AM); - assertTrue("Incorrect result 14: " + cal.getTime(), cal.getTime() - .getTime() == 1016686800000L); - - int hour = cal.get(Calendar.HOUR); - cal.set(Calendar.HOUR, hour); - cal.set(Calendar.AM_PM, Calendar.PM); - assertEquals("AM_PM not changed", Calendar.PM, cal.get(Calendar.AM_PM)); - // setting AM_PM without HOUR should not have any affect - cal.set(Calendar.AM_PM, Calendar.AM); - assertEquals("AM_PM was changed 1", - Calendar.AM, cal.get(Calendar.AM_PM)); - int hourOfDay = cal.get(Calendar.HOUR_OF_DAY); - hour = cal.get(Calendar.HOUR); - cal.set(Calendar.AM_PM, Calendar.PM); - assertEquals("AM_PM was changed 2", - Calendar.PM, cal.get(Calendar.AM_PM)); - assertEquals(hour, cal.get(Calendar.HOUR)); - assertEquals(hourOfDay + 12, cal.get(Calendar.HOUR_OF_DAY)); - - // regression test for Harmony-2122 - cal = Calendar.getInstance(); - int oldValue = cal.get(Calendar.AM_PM); - int newValue = (oldValue == Calendar.AM) ? Calendar.PM : Calendar.AM; - cal.set(Calendar.AM_PM, newValue); - newValue = cal.get(Calendar.AM_PM); - assertTrue(newValue != oldValue); - } - - /** - * java.util.Calendar#setTime(java.util.Date) - */ - public void test_setTimeLjava_util_Date() { - Calendar cal = Calendar.getInstance(); - // Use millisecond time for testing in Core - cal.setTime(new Date(884581200000L)); // (98, Calendar.JANUARY, 12) - assertEquals("incorrect millis", 884581200000L, cal.getTime().getTime()); - cal.setTimeZone(TimeZone.getTimeZone("EST")); - cal.setTime(new Date(943506000000L)); // (99, Calendar.NOVEMBER, 25) - assertTrue("incorrect fields", cal.get(Calendar.YEAR) == 1999 - && cal.get(Calendar.MONTH) == Calendar.NOVEMBER - && cal.get(Calendar.DATE) == 25); - } - - /** - * java.util.Calendar#compareTo(Calendar) - */ - public void test_compareToLjava_util_Calendar_null() { - Calendar cal = Calendar.getInstance(); - try { - cal.compareTo(null); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - } - - /** - * java.util.Calendar#compareTo(Calendar) - */ - public void test_compareToLjava_util_Calendar() { - Calendar cal = Calendar.getInstance(); - cal.clear(); - cal.set(1997, 12, 13, 23, 57); - - Calendar anotherCal = Calendar.getInstance(); - anotherCal.clear(); - anotherCal.set(1997, 12, 13, 23, 57); - assertEquals(0, cal.compareTo(anotherCal)); - - anotherCal = Calendar.getInstance(); - anotherCal.clear(); - anotherCal.set(1997, 11, 13, 24, 57); - assertEquals(1, cal.compareTo(anotherCal)); - - anotherCal = Calendar.getInstance(); - anotherCal.clear(); - anotherCal.set(1997, 12, 13, 23, 58); - assertEquals(-1, cal.compareTo(anotherCal)); - } - - /** - * java.util.Calendar#clone() - */ - public void test_clone() { - // Regression for HARMONY-475 - Calendar cal = Calendar.getInstance(); - cal.set(2006, 5, 6, 11, 35); - Calendar anotherCal = (Calendar) cal.clone(); - // should be deep clone - assertNotSame("getTimeZone", cal.getTimeZone(), anotherCal - .getTimeZone()); - } - - /** - * java.util.Calendar#getTimeInMillis() - */ - public void test_getTimeInMillis() { - Calendar cal = Calendar.getInstance(); - - int year = Integer.MIN_VALUE + 71; - cal.setTimeZone(TimeZone.getTimeZone("GMT")); - cal.set(Calendar.YEAR, year + 1900); - cal.set(Calendar.MONTH, Calendar.JANUARY); - cal.set(Calendar.DATE, 1); - cal.set(Calendar.HOUR_OF_DAY, 0); - cal.set(Calendar.MINUTE, 0); - cal.set(Calendar.SECOND, 0); - cal.set(Calendar.MILLISECOND, 0); - - assertEquals(6017546357372606464L, cal.getTimeInMillis()); - } - - private static final Locale[] locales = new Locale[] { Locale.getDefault(), - Locale.US, Locale.UK, Locale.TAIWAN, Locale.PRC, Locale.KOREA, - Locale.JAPAN, Locale.ITALIAN, Locale.GERMAN, Locale.ENGLISH, - Locale.CHINA, Locale.CANADA, Locale.FRANCE }; - - /** - * java.util.Calendar#before(Object) - * java.util.Calendar#after(Object) - */ - public void test_before_after() { - Calendar early = Calendar.getInstance(); - Calendar late = Calendar.getInstance(); - // test by second - early.set(2008, 3, 20, 17, 28, 12); - late.set(2008, 3, 20, 17, 28, 22); - // test before() - assertTrue(early.before(late)); - assertFalse(early.before(early)); - assertFalse(late.before(early)); - // test after(); - assertTrue(late.after(early)); - assertFalse(late.after(late)); - assertFalse(early.after(late)); - - // test by minute - early.set(2008, 3, 20, 17, 18, 12); - late.set(2008, 3, 20, 17, 28, 12); - // test before() - assertTrue(early.before(late)); - assertFalse(early.before(early)); - assertFalse(late.before(early)); - // test after(); - assertTrue(late.after(early)); - assertFalse(late.after(late)); - assertFalse(early.after(late)); - - // test by hour - early.set(2008, 3, 20, 17, 28, 12); - late.set(2008, 3, 20, 27, 28, 12); - // test before() - assertTrue(early.before(late)); - assertFalse(early.before(early)); - assertFalse(late.before(early)); - // test after(); - assertTrue(late.after(early)); - assertFalse(late.after(late)); - assertFalse(early.after(late)); - - // test by day - early.set(2008, 3, 10, 17, 28, 12); - late.set(2008, 3, 20, 17, 28, 12); - // test before() - assertTrue(early.before(late)); - assertFalse(early.before(early)); - assertFalse(late.before(early)); - // test after(); - assertTrue(late.after(early)); - assertFalse(late.after(late)); - assertFalse(early.after(late)); - - // test by month - early.set(2008, 2, 20, 17, 28, 12); - late.set(2008, 3, 20, 17, 28, 12); - // test before() - assertTrue(early.before(late)); - assertFalse(early.before(early)); - assertFalse(late.before(early)); - // test after(); - assertTrue(late.after(early)); - assertFalse(late.after(late)); - assertFalse(early.after(late)); - - // test by year - early.set(2007, 3, 20, 17, 28, 12); - late.set(2008, 3, 20, 17, 28, 12); - // test before() - assertTrue(early.before(late)); - assertFalse(early.before(early)); - assertFalse(late.before(early)); - // test after(); - assertTrue(late.after(early)); - assertFalse(late.after(late)); - assertFalse(early.after(late)); - } - - /** - * java.util.Calendar#clear() - * java.util.Calendar#clear(int) - */ - public void test_clear() { - Calendar calendar = Calendar.getInstance(); - - int count = 6; - int[] fields = new int[count]; - int[] defaults = new int[count]; - - fields[0] = Calendar.YEAR; - fields[1] = Calendar.MONTH; - fields[2] = Calendar.DATE; - fields[3] = Calendar.HOUR_OF_DAY; - fields[4] = Calendar.MINUTE; - fields[5] = Calendar.SECOND; - - defaults[0] = 1970; - defaults[1] = 0; - defaults[2] = 1; - defaults[3] = 0; - defaults[4] = 0; - defaults[5] = 0; - - calendar.set(2008, 3, 20, 17, 28, 12); - - // test clear(int) - for (int i = 0; i < fields.length; i++) { - int index = fields[i]; - calendar.clear(index); - if (5 == index) { - // RI also doesn't change the value of DATE - assertEquals("Field " + index + " Should equal to 20.", 20, - calendar.get(index)); - } else if (11 == index) { - // RI also doesn't change the value of HOUR - assertEquals("Field " + index + " Should equal to 17.", 17, - calendar.get(index)); - } else { - // Other have been set to default values - assertEquals("Field " + index + " Should equal to " - + defaults[i] + ".", defaults[i], calendar.get(index)); - } - } - - // test clear() - calendar.set(2008, 3, 20, 17, 28, 12); - - calendar.clear(); - - for (int i = 0; i < fields.length; i++) { - int index = fields[i]; - assertEquals("Field " + index + " Should equal to " - + defaults[i] + ".", defaults[i], calendar.get(index)); - } - } - - /** - * java.util.Calendar#isSet(int) - */ - public void test_isSet() { - Calendar calendar = Calendar.getInstance(); - calendar.clear(); - for (int i = 0; i < Calendar.FIELD_COUNT; i++) { - assertFalse(calendar.isSet(i)); - } - } - - /** - * java.util.Calendar#getAvailableLocales() - */ - public void test_getAvailableLocales() { - Locale[] locales = Calendar.getAvailableLocales(); - boolean exist = false; - for (int i = 0; i < locales.length; i++) { - Locale l = locales[i]; - if (Locale.US.equals(l)) { - exist = true; - break; - } - } - assertTrue(exist); - } - - /** - * java.util.Calendar#getInstance(Locale) - * java.util.Calendar#getInstance(TimeZone, Locale) - */ - public void test_getInstance() { - // test getInstance(Locale) - Calendar us_calendar = Calendar.getInstance(Locale.US); - Calendar de_calendar = Calendar.getInstance(Locale.GERMAN); - assertEquals(Calendar.SUNDAY, us_calendar - .getFirstDayOfWeek()); - assertEquals(Calendar.MONDAY, de_calendar - .getFirstDayOfWeek()); - - // test getInstance(Locale, TimeZone) - Calendar gmt_calendar = Calendar.getInstance(TimeZone - .getTimeZone("GMT"), Locale.US); - assertEquals(TimeZone.getTimeZone("GMT"), - gmt_calendar.getTimeZone()); - Calendar est_calendar = Calendar.getInstance(TimeZone - .getTimeZone("EST"), Locale.US); - assertEquals(TimeZone.getTimeZone("EST") - .getID(), est_calendar.getTimeZone().getID()); - } - - /** - * java.util.Calendar#internalGet(int) - */ - public void test_internalGet() { - MockGregorianCalendar c = new MockGregorianCalendar(); - c.clear(Calendar.YEAR); - assertEquals(0, c.internal_get(Calendar.YEAR)); - } - - /** - * java.util.Calendar#hashCode() - */ - public void test_hashcode() { - Calendar calendar = Calendar.getInstance(Locale.JAPAN); - assertTrue(calendar.hashCode() == calendar.hashCode()); - } - - /** - * java.util.Calendar#roll(int, int) - */ - public void test_roll() { - Calendar calendar = Calendar.getInstance(); - calendar.set(2008, 3, 20, 17, 28, 12); - - // roll up - calendar.roll(Calendar.DATE, 5); - assertEquals(25, calendar.get(Calendar.DATE)); - - // roll down - calendar.roll(Calendar.DATE, -5); - assertEquals(20, calendar.get(Calendar.DATE)); - - // roll 0 - calendar.roll(Calendar.DATE, 0); - assertEquals(20, calendar.get(Calendar.DATE)); - - // roll overweight - calendar.set(2008, 1, 31, 17, 28, 12); - calendar.roll(Calendar.MONTH, 1); - assertEquals(2, calendar.get(Calendar.DATE)); - - } - - /** - * java.util.Calendar#toString() - */ - public void test_toString() { - Calendar calendar = Calendar.getInstance(); - //Should be the current time with no interrogation in the string. - assertTrue(calendar.toString() instanceof String); - assertEquals(-1, calendar.toString().indexOf("?")); - calendar.clear(); - assertTrue(calendar.toString() instanceof String); - assertTrue(0 <= calendar.toString().indexOf("?")); - } - - /** - * serialization/deserialization. - */ - public void testSerializationSelf() throws Exception { - Calendar calendar = Calendar.getInstance(); - calendar.set(2008, 3, 20, 17, 28, 12); - - SerializationTest.verifySelf(calendar); - } - - - private class MockGregorianCalendar extends GregorianCalendar { - public int internal_get(int field) { - return super.internalGet(field); - } - } - - private class MockCalendar extends Calendar { - - public MockCalendar() { - super(); - } - - @Override - public void add(int field, int value) { - } - - @Override - protected void computeFields() { - } - - @Override - protected void computeTime() { - } - - @Override - public int getGreatestMinimum(int field) { - return 0; - } - - @Override - public int getLeastMaximum(int field) { - return 0; - } - - @Override - public int getMaximum(int field) { - return 0; - } - - @Override - public int getMinimum(int field) { - return 0; - } - - @Override - public void roll(int field, boolean increment) { - } - } - - /** - * {@link java.util.Calendar#getDisplayName(int, int, Locale)} - * @since 1.6 - */ - public void test_getDisplayNameIILjava_util_Locale() { - Calendar cal = Calendar.getInstance(); - for (int field = 0; field < Calendar.FIELD_COUNT; field++) { - for (Locale locale : locales) { - DateFormatSymbols symbols = new DateFormatSymbols(locale); - String value = null; - switch (field) { - case Calendar.AM_PM: - cal.set(Calendar.AM_PM, Calendar.AM); - value = symbols.getAmPmStrings()[0]; - assertEquals(cal.getDisplayName(field, Calendar.SHORT, - locale), value); - assertEquals(cal.getDisplayName(field, Calendar.LONG, - locale), value); - cal.set(Calendar.AM_PM, Calendar.PM); - value = symbols.getAmPmStrings()[1]; - assertEquals(cal.getDisplayName(field, Calendar.SHORT, - locale), value); - assertEquals(cal.getDisplayName(field, Calendar.LONG, - locale), value); - break; - case Calendar.ERA: - cal.set(Calendar.ERA, GregorianCalendar.BC); - value = symbols.getEras()[0]; - assertEquals(cal.getDisplayName(field, Calendar.SHORT, - locale), value); - assertEquals(cal.getDisplayName(field, Calendar.LONG, - locale), value); - cal.set(Calendar.ERA, GregorianCalendar.AD); - value = symbols.getEras()[1]; - assertEquals(cal.getDisplayName(field, Calendar.SHORT, - locale), value); - assertEquals(cal.getDisplayName(field, Calendar.LONG, - locale), value); - break; - case Calendar.MONTH: - cal.set(Calendar.DAY_OF_MONTH, 1); - for (int month = 0; month <= 11; month++) { - cal.set(Calendar.MONTH, month); - value = symbols.getShortMonths()[month]; - assertEquals(cal.getDisplayName(field, Calendar.SHORT, - locale), value); - value = symbols.getMonths()[month]; - assertEquals(cal.getDisplayName(field, Calendar.LONG, - locale), value); - } - break; - case Calendar.DAY_OF_WEEK: - for (int day = 1; day <= 7; day++) { - cal.set(Calendar.DAY_OF_WEEK, day); - value = symbols.getShortWeekdays()[day]; - assertEquals(cal.getDisplayName(field, Calendar.SHORT, - locale), value); - value = symbols.getWeekdays()[day]; - assertEquals(cal.getDisplayName(field, Calendar.LONG, - locale), value); - } - break; - default: - assertNull(cal - .getDisplayName(field, Calendar.SHORT, locale)); - assertNull(cal.getDisplayName(field, Calendar.LONG, locale)); - } - } - } - - cal.setLenient(true); - - try { - cal.getDisplayName(-1, Calendar.SHORT, Locale.US); - fail("Should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - try { - cal.getDisplayName(Calendar.FIELD_COUNT, Calendar.LONG, Locale.US); - fail("Should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - try { - cal.getDisplayName(Calendar.MONTH, -1, Locale.US); - fail("Should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - try { - cal.getDisplayName(Calendar.MONTH, 3, Locale.US); - fail("Should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - try { - cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, null); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - try { - cal.getDisplayName(-1, Calendar.SHORT, null); - fail("Should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - try { - cal.getDisplayName(Calendar.MONTH, -1, null); - fail("Should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - // in lenient mode, following cases pass - cal.set(Calendar.SECOND, 999); - cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.US); - // test for ALL_STYLES, it is equal to use SHORT - for (int field = 0; field < Calendar.FIELD_COUNT; field++) { - for (Locale locale : locales) { - String result = cal.getDisplayName(field, Calendar.ALL_STYLES, - locale); - if (field == Calendar.AM_PM || field == Calendar.ERA - || field == Calendar.MONTH - || field == Calendar.DAY_OF_WEEK) { - assertEquals(result, cal.getDisplayName(field, - Calendar.SHORT, locale)); - } else { - assertNull(result); - } - } - } - - // invalid value for an un-related field when the calendar is not - // lenient - cal.setLenient(false); - assertNotNull(cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, - Locale.US)); - cal.set(Calendar.SECOND, 999); - try { - cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.US); - fail("Should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - try { - cal.getDisplayName(Calendar.MONTH, Calendar.ALL_STYLES, Locale.US); - fail("Should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - } - - /** - * {@link java.util.Calendar#getDisplayNames(int, int, Locale)} - * @since 1.6 - */ - public void test_getDisplayNamesIILjava_util_Locale() { - assertEquals(0, Calendar.ALL_STYLES); - assertEquals(1, Calendar.SHORT); - assertEquals(2, Calendar.LONG); - - Calendar cal = Calendar.getInstance(Locale.US); - - for (int field = 0; field < Calendar.FIELD_COUNT; field++) { - for (Locale locale : locales) { - Map<String, Integer> shortResult = cal.getDisplayNames(field, - Calendar.SHORT, locale); - Map<String, Integer> longResult = cal.getDisplayNames(field, - Calendar.LONG, locale); - Map<String, Integer> allResult = cal.getDisplayNames(field, - Calendar.ALL_STYLES, locale); - DateFormatSymbols symbols = new DateFormatSymbols(locale); - String[] values = null; - switch (field) { - case Calendar.AM_PM: - case Calendar.ERA: - values = (field == Calendar.AM_PM) ? symbols - .getAmPmStrings() : symbols.getEras(); - assertDisplayNameMap(values, shortResult, 0); - assertDisplayNameMap(values, longResult, 0); - assertDisplayNameMap(values, allResult, 0); - break; - case Calendar.MONTH: - values = symbols.getShortMonths(); - assertDisplayNameMap(values, shortResult, 0); - values = symbols.getMonths(); - assertDisplayNameMap(values, longResult, 0); - assertTrue(allResult.size() >= shortResult.size()); - assertTrue(allResult.size() >= longResult.size()); - assertTrue(allResult.size() <= shortResult.size() - + longResult.size()); - break; - case Calendar.DAY_OF_WEEK: - values = symbols.getShortWeekdays(); - assertDisplayNameMap(values, shortResult, 1); - values = symbols.getWeekdays(); - assertDisplayNameMap(values, longResult, 1); - assertTrue(allResult.size() >= shortResult.size()); - assertTrue(allResult.size() >= longResult.size()); - assertTrue(allResult.size() <= shortResult.size() - + longResult.size()); - break; - default: - assertNull(shortResult); - assertNull(longResult); - assertNull(allResult); - } - } - } - - cal.setLenient(true); - - try { - cal.getDisplayNames(-1, Calendar.SHORT, Locale.US); - fail("Should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - try { - cal.getDisplayNames(Calendar.FIELD_COUNT, Calendar.LONG, Locale.US); - fail("Should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - try { - cal.getDisplayNames(Calendar.MONTH, -1, Locale.US); - fail("Should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - try { - cal.getDisplayNames(Calendar.MONTH, 3, Locale.US); - fail("Should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - try { - cal.getDisplayNames(Calendar.MONTH, Calendar.SHORT, null); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - try { - cal.getDisplayNames(-1, Calendar.SHORT, null); - fail("Should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - try { - cal.getDisplayNames(Calendar.MONTH, -1, null); - fail("Should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - cal.set(Calendar.SECOND, 999); - cal.getDisplayNames(Calendar.MONTH, Calendar.SHORT, Locale.US); - - // RI fails here - // invalid value for an un-related field when the calendar is not - // lenient - cal.setLenient(false); - cal.set(Calendar.SECOND, 999); - try { - cal.getDisplayNames(Calendar.MONTH, Calendar.SHORT, Locale.US); - fail("Should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - } - - private void assertDisplayNameMap(String[] values, - Map<String, Integer> result, int shift) { - List<String> trimValue = new ArrayList<String>(); - for (String value : values) { - if (value.trim().length() > 0) { - trimValue.add(value); - } - } - assertEquals(trimValue.size(), result.size()); - for (int i = 0; i < trimValue.size(); i++) { - assertEquals(i + shift, result.get(trimValue.get(i)).intValue()); - } - } - - /** - * {@link java.util.Calendar#getActualMaximum(int)} - */ - public void test_getActualMaximum_I() { - Calendar c = new MockCalendar(); - assertEquals("should be equal to 0", 0, c.getActualMaximum(0)); - } - - /** - * {@link java.util.Calendar#getActualMinimum(int)} - */ - public void test_getActualMinimum_I() { - Calendar c = new MockCalendar(); - assertEquals("should be equal to 0", 0, c.getActualMinimum(0)); - } - - protected void setUp() { - defaultLocale = Locale.getDefault(); - Locale.setDefault(Locale.US); - } - - protected void tearDown() { - Locale.setDefault(defaultLocale); - } -} diff --git a/luni/src/test/java/tests/api/java/util/CollectionsTest.java b/luni/src/test/java/tests/api/java/util/CollectionsTest.java deleted file mode 100644 index c308cf9..0000000 --- a/luni/src/test/java/tests/api/java/util/CollectionsTest.java +++ /dev/null @@ -1,2226 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Random; -import java.util.RandomAccess; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeMap; -import java.util.TreeSet; -import java.util.Arrays; - -import tests.support.Support_CollectionTest; -import tests.support.Support_ListTest; -import tests.support.Support_SetTest; -import tests.support.Support_UnmodifiableCollectionTest; -import tests.support.Support_UnmodifiableMapTest; - -public class CollectionsTest extends junit.framework.TestCase { - - private LinkedList ll; - - private LinkedList myll; - - private LinkedList reversedLinkedList; - - private LinkedList myReversedLinkedList; - - private Set s; - - private Set mys; - - private HashMap hm; - - private Object[] objArray; - - private Object[] myobjArray; - - public static class ReversedMyIntComparator implements Comparator { - public int compare(Object o1, Object o2) { - return -((MyInt) o1).compareTo((MyInt) o2); - } - - public int equals(Object o1, Object o2) { - return ((MyInt) o1).compareTo((MyInt) o2); - } - } - - public static class SynchCollectionChecker implements Runnable { - Collection col; - - int colSize; - - int totalToRun; - - boolean offset; - - volatile int numberOfChecks = 0; - - boolean result = true; - - ArrayList normalCountingList; - - ArrayList offsetCountingList; - - public void run() { - // ensure the list either contains the numbers from 0 to size-1 or - // the numbers from size to 2*size -1 - while (numberOfChecks < totalToRun) { - synchronized (col) { - if (!(col.isEmpty() || col.containsAll(normalCountingList) || col - .containsAll(offsetCountingList))) - result = false; - col.clear(); - } - if (offset) - col.addAll(offsetCountingList); - else - col.addAll(normalCountingList); - numberOfChecks++; - } - } - - public SynchCollectionChecker(Collection c, boolean offset, - int totalChecks) { - // The collection to test, whether to offset the filler values by - // size or not, and the min number of iterations to run - totalToRun = totalChecks; - col = c; - colSize = c.size(); - normalCountingList = new ArrayList(colSize); - offsetCountingList = new ArrayList(colSize); - for (int counter = 0; counter < colSize; counter++) - normalCountingList.add(new Integer(counter)); - for (int counter = 0; counter < colSize; counter++) - offsetCountingList.add(new Integer(counter + colSize)); - col.clear(); - if (offset) - col.addAll(offsetCountingList); - else - col.addAll(normalCountingList); - } - - public boolean offset() { - // answer true iff the list is filled with a counting sequence - // starting at the value size to 2*size - 1 - // else the list with be filled starting at 0 to size - 1 - return offset; - } - - public boolean getResult() { - // answer true iff no corruption has been found in the collection - return result; - } - - public int getNumberOfChecks() { - // answer the number of checks that have been performed on the list - return numberOfChecks; - } - } - - public static class SynchMapChecker implements Runnable { - Map map; - - int mapSize; - - int totalToRun; - - boolean offset; - - volatile int numberOfChecks = 0; - - boolean result = true; - - Map normalCountingMap; - - Map offsetCountingMap; - - public void run() { - Object firstNormalValue = normalCountingMap.get(new Integer(0)); - Object lastNormalValue = normalCountingMap.get(new Integer( - mapSize - 1)); - Object firstOffsetValue = offsetCountingMap - .get(new Integer(mapSize)); - Object lastOffsetValue = offsetCountingMap.get(new Integer( - 2 * mapSize - 1)); - // ensure the list either contains the numbers from 0 to size-1 or - // the numbers from size to 2*size -1 - while (numberOfChecks < totalToRun) { - synchronized (map) { - if (!(map.isEmpty() - || (map.containsValue(firstNormalValue) && map - .containsValue(lastNormalValue)) || (map - .containsValue(firstOffsetValue) && map - .containsValue(lastOffsetValue)))) - result = false; - map.clear(); - } - if (offset) - map.putAll(offsetCountingMap); - else - map.putAll(normalCountingMap); - numberOfChecks++; - } - } - - public SynchMapChecker(Map m, boolean offset, int totalChecks) { - // The collection to test, whether to offset the filler values by - // size or not, and the min number of iterations to run - Integer myInt; - totalToRun = totalChecks; - map = m; - mapSize = m.size(); - normalCountingMap = new HashMap(mapSize); - offsetCountingMap = new HashMap(mapSize); - for (int counter = 0; counter < mapSize; counter++) { - myInt = new Integer(counter); - normalCountingMap.put(myInt, myInt); - } - for (int counter = 0; counter < mapSize; counter++) { - myInt = new Integer(counter + mapSize); - offsetCountingMap.put(myInt, myInt); - } - map.clear(); - if (offset) - map.putAll(offsetCountingMap); - else - map.putAll(normalCountingMap); - } - - public boolean offset() { - // answer true iff the list is filled with a counting sequence - // starting at the value size to 2*size - 1 - // else the list with be filled starting at 0 to size - 1 - return offset; - } - - public boolean getResult() { - // answer true iff no corruption has been found in the collection - return result; - } - - public int getNumberOfChecks() { - // answer the number of checks that have been performed on the list - return numberOfChecks; - } - } - - public static class CollectionTest extends junit.framework.TestCase { - - Collection col; // must contain the Integers 0 to 99 - - public CollectionTest(String p1) { - super(p1); - } - - public CollectionTest(String p1, Collection c) { - super(p1); - col = c; - } - - } - - static class MyInt { - int data; - - public MyInt(int value) { - data = value; - } - - public int compareTo(MyInt object) { - return data > object.data ? 1 : (data < object.data ? -1 : 0); - } - } - - /** - * java.util.Collections#binarySearch(java.util.List, - * java.lang.Object) - */ - public void test_binarySearchLjava_util_ListLjava_lang_Object() { - // Test for method int - // java.util.Collections.binarySearch(java.util.List, java.lang.Object) - // assumes ll is sorted and has no duplicate keys - final int llSize = ll.size(); - // Ensure a NPE is thrown if the list is NULL - try { - Collections.binarySearch(null, new Object()); - fail("Expected NullPointerException for null list parameter"); - } catch (NullPointerException e) { - } - for (int counter = 0; counter < llSize; counter++) { - assertTrue("Returned incorrect binary search item position", ll - .get(Collections.binarySearch(ll, ll.get(counter))) == ll - .get(counter)); - } - } - - /** - * java.util.Collections#binarySearch(java.util.List, - * java.lang.Object, java.util.Comparator) - */ - public void test_binarySearchLjava_util_ListLjava_lang_ObjectLjava_util_Comparator() { - // Test for method int - // java.util.Collections.binarySearch(java.util.List, java.lang.Object, - // java.util.Comparator) - // assumes reversedLinkedList is sorted in reversed order and has no - // duplicate keys - final int rSize = myReversedLinkedList.size(); - ReversedMyIntComparator comp = new ReversedMyIntComparator(); - // Ensure a NPE is thrown if the list is NULL - try { - Collections.binarySearch(null, new Object(), comp); - fail("Expected NullPointerException for null list parameter"); - } catch (NullPointerException e) { - } - for (int counter = 0; counter < rSize; counter++) { - assertTrue( - "Returned incorrect binary search item position using custom comparator", - myReversedLinkedList.get(Collections.binarySearch( - myReversedLinkedList, myReversedLinkedList - .get(counter), comp)) == myReversedLinkedList - .get(counter)); - } - } - - class Mock_ArrayList extends ArrayList { - @Override - public - Object set (int index, Object o){ - throw new UnsupportedOperationException(); - } - } - - /** - * java.util.Collections#copy(java.util.List, java.util.List) - */ - public void test_copyLjava_util_ListLjava_util_List() { - // Test for method void java.util.Collections.copy(java.util.List, - // java.util.List) - // Ensure a NPE is thrown if the list is NULL - try { - Collections.copy(null, ll); - fail("Expected NullPointerException for null list first parameter"); - } catch (NullPointerException e) { - } - try { - Collections.copy(ll, null); - fail("Expected NullPointerException for null list second parameter"); - } catch (NullPointerException e) { - } - final int llSize = ll.size(); - ll.set(25, null); - ArrayList al = new ArrayList(); - Integer extraElement = new Integer(1); - Integer extraElement2 = new Integer(2); - al.addAll(myReversedLinkedList); - al.add(extraElement); - al.add(extraElement2); - Collections.copy(al, ll); - for (int counter = 0; counter < llSize; counter++) { - assertTrue("Elements do not match after copying collection", al - .get(counter) == ll.get(counter)); - } - assertTrue("Elements after copied elements affected by copy", - extraElement == al.get(llSize) - && extraElement2 == al.get(llSize + 1)); - - ArrayList ar1 = new ArrayList(); - ArrayList ar2 = new ArrayList(); - - int i; - - for(i = 0; i < 5; i ++) { - ar2.add(new Integer(i)); - } - - for(i = 0; i < 10; i ++) { - ar1.add(new Integer(i)); - } - - try { - Collections.copy(ar2, ar1); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - //expected - } - - Mock_ArrayList mal1 = new Mock_ArrayList(); - Mock_ArrayList mal2 = new Mock_ArrayList(); - - for(i = 0; i < 10; i ++) { - mal1.add(new Integer(i)); - mal2.add(new Integer(10 - i)); - } - - try { - Collections.copy(mal1, mal2); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException e) { - //expected - } - } - - /** - * java.util.Collections#copy(java.util.List, java.util.List) - */ - public void test_copy_check_index() { - ArrayList a1 = new ArrayList(); - a1.add("one"); - a1.add("two"); - - ArrayList a2 = new ArrayList(); - a2.add("aa"); - - try { - Collections.copy(a2, a1); - fail("Expected IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - } - - assertEquals("aa", a2.get(0)); - } - - /** - * java.util.Collections#enumeration(java.util.Collection) - */ - public void test_enumerationLjava_util_Collection() { - // Test for method java.util.Enumeration - // java.util.Collections.enumeration(java.util.Collection) - TreeSet ts = new TreeSet(); - ts.addAll(s); - Enumeration e = Collections.enumeration(ts); - int count = 0; - while (e.hasMoreElements()) - assertTrue("Returned incorrect enumeration", - e.nextElement() == objArray[count++]); - assertTrue("Enumeration missing elements: " + count, - count == objArray.length); - } - - /** - * java.util.Collections#fill(java.util.List, java.lang.Object) - */ - public void test_fillLjava_util_ListLjava_lang_Object() { - // Test for method void java.util.Collections.fill(java.util.List, - // java.lang.Object) - try { - Collections.fill(null, new Object()); - fail("Expected NullPointerException for null list parameter"); - } catch (NullPointerException e) { - } - final int size = ll.size(); - Collections.fill(ll, "k"); - assertTrue("Fill modified list size", size == ll.size()); - Iterator i = ll.iterator(); - while (i.hasNext()) - assertEquals("Failed to fill elements", "k", i.next()); - - Collections.fill(ll, null); - assertTrue("Fill with nulls modified list size", size == ll.size()); - i = ll.iterator(); - while (i.hasNext()) - assertNull("Failed to fill with nulls", i.next()); - - Mock_ArrayList mal = new Mock_ArrayList(); - - mal.add("one"); - mal.add("two"); - - try { - Collections.fill(mal, "value"); - fail("UnsupportedOperationException ecpected"); - } catch (UnsupportedOperationException e) { - //expected - } - } - - /** - * java.util.Collections#max(java.util.Collection) - */ - public void test_maxLjava_util_Collection() { - // Test for method java.lang.Object - // java.util.Collections.max(java.util.Collection) - // assumes s, objArray are sorted - assertTrue("Returned incorrect max element", - Collections.max(s) == objArray[objArray.length - 1]); - - ArrayList al = new ArrayList(); - - try { - Collections.max(al); - fail("NoSuchElementException expected"); - } catch (NoSuchElementException e) { - //expected - } - - al.add("String"); - al.add(new Integer(1)); - al.add(new Double(3.14)); - - try { - Collections.max(al); - fail("ClassCastException expected"); - } catch (ClassCastException e) { - //expected - } - } - - /** - * java.util.Collections#max(java.util.Collection, - * java.util.Comparator) - */ - public void test_maxLjava_util_CollectionLjava_util_Comparator() { - // Test for method java.lang.Object - // java.util.Collections.max(java.util.Collection, java.util.Comparator) - // assumes s, objArray are sorted - - // With this custom (backwards) comparator the 'max' element should be - // the smallest in the list - ReversedMyIntComparator rmic = new ReversedMyIntComparator(); - assertTrue( - "Returned incorrect max element using custom comparator", - Collections.max(mys, rmic) == myobjArray[0]); - - ArrayList al = new ArrayList(); - - try { - Collections.max(al, rmic); - fail("NoSuchElementException expected"); - } catch (NoSuchElementException e) { - //expected - } - - al.add("String"); - al.add(new Integer(1)); - al.add(new Double(3.14)); - - try { - Collections.max(al, rmic); - fail("ClassCastException expected"); - } catch (ClassCastException e) { - //expected - } - } - - /** - * java.util.Collections#min(java.util.Collection) - */ - public void test_minLjava_util_Collection() { - // Test for method java.lang.Object - // java.util.Collections.min(java.util.Collection) - // assumes s, objArray are sorted - assertTrue("Returned incorrect min element", - Collections.min(s) == objArray[0]); - ArrayList al = new ArrayList(); - - try { - Collections.min(al); - fail("NoSuchElementException expected"); - } catch (NoSuchElementException e) { - //expected - } - - al.add("String"); - al.add(new Integer(1)); - al.add(new Double(3.14)); - - try { - Collections.min(al); - fail("ClassCastException expected"); - } catch (ClassCastException e) { - //expected - } - } - - /** - * java.util.Collections#min(java.util.Collection, - * java.util.Comparator) - */ - public void test_minLjava_util_CollectionLjava_util_Comparator() { - // Test for method java.lang.Object - // java.util.Collections.min(java.util.Collection, java.util.Comparator) - // assumes s, objArray are sorted - - // With this custom (backwards) comparator the 'min' element should be - // the largest in the list - ReversedMyIntComparator rmic = new ReversedMyIntComparator(); - - assertTrue( - "Returned incorrect min element using custom comparator", - Collections.min(mys, rmic) == myobjArray[objArray.length - 1]); - - ArrayList al = new ArrayList(); - - try { - Collections.min(al, rmic); - fail("NoSuchElementException expected"); - } catch (NoSuchElementException e) { - //expected - } - - al.add("String"); - al.add(new Integer(1)); - al.add(new Double(3.14)); - - try { - Collections.min(al, rmic); - fail("ClassCastException expected"); - } catch (ClassCastException e) { - //expected - } - } - - /** - * java.util.Collections#nCopies(int, java.lang.Object) - */ - public void test_nCopiesILjava_lang_Object() { - // Test for method java.util.List java.util.Collections.nCopies(int, - // java.lang.Object) - Object o = new Object(); - List l = Collections.nCopies(100, o); - Iterator i = l.iterator(); - Object first = i.next(); - assertTrue("Returned list consists of copies not refs", first == o); - assertEquals("Returned list of incorrect size", 100, l.size()); - assertTrue("Contains", l.contains(o)); - assertTrue("Contains null", !l.contains(null)); - assertTrue("null nCopies contains", !Collections.nCopies(2, null) - .contains(o)); - assertTrue("null nCopies contains null", Collections.nCopies(2, null) - .contains(null)); - l = Collections.nCopies(20, null); - i = l.iterator(); - for (int counter = 0; i.hasNext(); counter++) { - assertTrue("List is too large", counter < 20); - assertNull("Element should be null: " + counter, i.next()); - } - try { - l.add(o); - fail("Returned list is not immutable"); - } catch (UnsupportedOperationException e) { - // Correct - return; - } - try { - Collections.nCopies(-2, new HashSet()); - fail("nCopies with negative arg didn't throw IAE"); - } catch (IllegalArgumentException e) { - // Expected - } - } - - /** - * java.util.Collections#reverse(java.util.List) - */ - public void test_reverseLjava_util_List() { - // Test for method void java.util.Collections.reverse(java.util.List) - try { - Collections.reverse(null); - fail("Expected NullPointerException for null list parameter"); - } catch (NullPointerException e) { - } - Collections.reverse(ll); - Iterator i = ll.iterator(); - int count = objArray.length - 1; - while (i.hasNext()) { - assertTrue("Failed to reverse collection", - i.next() == objArray[count]); - --count; - } - ArrayList myList = new ArrayList(); - myList.add(null); - myList.add(new Integer(20)); - Collections.reverse(myList); - assertTrue("Did not reverse correctly--first element is: " - + myList.get(0), myList.get(0).equals(new Integer(20))); - assertNull("Did not reverse correctly--second element is: " - + myList.get(1), myList.get(1)); - - Mock_ArrayList mal = new Mock_ArrayList(); - - mal.add("First"); - mal.add("Second"); - - try { - Collections.reverse(mal); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException e) { - //expected - } - } - - /** - * java.util.Collections#reverseOrder() - */ - public void test_reverseOrder() { - // Test for method java.util.Comparator - // java.util.Collections.reverseOrder() - // assumes no duplicates in ll - Comparator comp = Collections.reverseOrder(); - LinkedList list2 = new LinkedList(ll); - Collections.sort(list2, comp); - final int llSize = ll.size(); - for (int counter = 0; counter < llSize; counter++) - assertTrue("New comparator does not reverse sorting order", ll - .get(counter) == list2.get(llSize - counter - 1)); - } - - /** - * java.util.Collections#shuffle(java.util.List) - */ - public void test_shuffleLjava_util_List() { - // Test for method void java.util.Collections.shuffle(java.util.List) - // Assumes ll is sorted and has no duplicate keys and is large ( > 20 - // elements) - - // test shuffling a Sequential Access List - try { - Collections.shuffle(null); - fail("Expected NullPointerException for null list parameter"); - } catch (NullPointerException e) { - } - ArrayList al = new ArrayList(); - al.addAll(ll); - testShuffle(al, "Sequential Access", false); - - // test shuffling a Random Access List - LinkedList ll2 = new LinkedList(); - ll2.addAll(ll); - testShuffle(ll2, "Random Access", false); - } - - public void testShuffleRandomAccessWithSeededRandom() { - List<String> list = Arrays.asList("A", "B", "C", "D", "E", "F", "G"); - Collections.shuffle(list, new Random(0)); - assertEquals(Arrays.asList("B", "A", "D", "C", "G", "E", "F"), list); - } - - public void testShuffleWithSeededRandom() { - List<String> list = new LinkedList<String>(Arrays.asList( - "A", "B", "C", "D", "E", "F", "G")); - Collections.shuffle(list, new Random(0)); - assertEquals(Arrays.asList("B", "A", "D", "C", "G", "E", "F"), list); - } - - private void testShuffle(List list, String type, boolean random) { - boolean sorted = true; - boolean allMatch = true; - int index = 0; - final int size = list.size(); - - if (random) - Collections.shuffle(list); - else - Collections.shuffle(list, new Random(200)); - - for (int counter = 0; counter < size - 1; counter++) { - if (((Integer) list.get(counter)).compareTo((Integer)list.get(counter + 1)) > 0) { - sorted = false; - } - } - assertFalse("Shuffling sorted " + type - + " list resulted in sorted list (should be unlikely)", sorted); - for (int counter = 0; counter < 20; counter++) { - index = 30031 * counter % (size + 1); // 30031 is a large prime - if (list.get(index) != ll.get(index)) - allMatch = false; - } - assertFalse("Too many element positions match in shuffled " + type - + " list", allMatch); - } - - /** - * java.util.Collections#shuffle(java.util.List, java.util.Random) - */ - public void test_shuffleLjava_util_ListLjava_util_Random() { - // Test for method void java.util.Collections.shuffle(java.util.List, - // java.util.Random) - // Assumes ll is sorted and has no duplicate keys and is large ( > 20 - // elements) - - // test shuffling a Sequential Access List - try { - Collections.shuffle(null, new Random(200)); - fail("Expected NullPointerException for null list parameter"); - } catch (NullPointerException e) { - } - ArrayList al = new ArrayList(); - al.addAll(ll); - testShuffle(al, "Sequential Access", true); - - // test shuffling a Random Access List - LinkedList ll2 = new LinkedList(); - ll2.addAll(ll); - testShuffle(ll2, "Random Access", true); - - - Mock_ArrayList mal = new Mock_ArrayList(); - - mal.add("First"); - mal.add("Second"); - - try { - Collections.shuffle(mal, new Random(200)); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException e) { - //expected - } -} - - /** - * java.util.Collections#singleton(java.lang.Object) - */ - public void test_singletonLjava_lang_Object() { - // Test for method java.util.Set - // java.util.Collections.singleton(java.lang.Object) - Object o = new Object(); - Set single = Collections.singleton(o); - assertEquals("Wrong size", 1, single.size()); - assertTrue("Contains", single.contains(o)); - assertTrue("Contains null", !single.contains(null)); - assertTrue("null nCopies contains", !Collections.singleton(null) - .contains(o)); - assertTrue("null nCopies contains null", Collections.singleton(null) - .contains(null)); - try { - single.add("l"); - } catch (UnsupportedOperationException e) { - // Correct - return; - } - fail("Allowed modification of singleton"); - } - - /** - * java.util.Collections#sort(java.util.List) - */ - public void test_sortLjava_util_List() { - // Test for method void java.util.Collections.sort(java.util.List) - // assumes no duplicate keys in ll - final int llSize = ll.size(); - final int rllSize = reversedLinkedList.size(); - try { - Collections.sort((List)null); - fail("Expected NullPointerException for null list parameter"); - } catch (NullPointerException e) { - } - Collections.shuffle(ll); - Collections.sort(ll); - Collections.sort(reversedLinkedList); - for (int counter = 0; counter < llSize - 1; counter++) { - assertTrue( - "Sorting shuffled list resulted in unsorted list", - ((Integer) ll.get(counter)).compareTo((Integer)ll.get(counter + 1)) < 0); - } - - for (int counter = 0; counter < rllSize - 1; counter++) { - assertTrue("Sorting reversed list resulted in unsorted list", - ((Integer) reversedLinkedList.get(counter)) - .compareTo((Integer)reversedLinkedList.get(counter + 1)) < 0); - } - - ArrayList al = new ArrayList(); - - al.add("String"); - al.add(new Integer(1)); - al.add(new Double(3.14)); - - try { - Collections.sort(al); - fail("ClassCastException expected"); - } catch (ClassCastException e) { - //expected - } - - Mock_ArrayList mal = new Mock_ArrayList(); - - mal.add("First"); - mal.add("Second"); - - try { - Collections.sort(mal); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException e) { - //expected - } - } - - /** - * java.util.Collections#sort(java.util.List, java.util.Comparator) - */ - public void test_sortLjava_util_ListLjava_util_Comparator() { - // Test for method void java.util.Collections.sort(java.util.List, - // java.util.Comparator) - Comparator comp = new ReversedMyIntComparator(); - try { - Collections.sort(null, comp); - fail("Expected NullPointerException for null list parameter"); - } catch (NullPointerException e) { - } - Collections.shuffle(myll); - Collections.sort(myll, comp); - final int llSize = myll.size(); - - for (int counter = 0; counter < llSize - 1; counter++) { - assertTrue( - "Sorting shuffled list with custom comparator resulted in unsorted list", - ((MyInt) myll.get(counter)).compareTo((MyInt) myll - .get(counter + 1)) >= 0); - } - - ArrayList al = new ArrayList(); - - al.add("String"); - al.add(new Integer(1)); - al.add(new Double(3.14)); - - try { - Collections.sort(al, comp); - fail("ClassCastException expected"); - } catch (ClassCastException e) { - //expected - } - - Mock_ArrayList mal = new Mock_ArrayList(); - - mal.add(new MyInt(1)); - mal.add(new MyInt(2)); - - try { - Collections.sort(mal, comp); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException e) { - //expected - } - } - - /** - * java.util.Collections#swap(java.util.List, int, int) - */ - public void test_swapLjava_util_ListII() { - // Test for method swap(java.util.List, int, int) - - LinkedList smallList = new LinkedList(); - for (int i = 0; i < 10; i++) { - smallList.add(objArray[i]); - } - - // test exception cases - try { - Collections.swap(smallList, -1, 6); - fail("Expected IndexOutOfBoundsException for -1"); - } catch (IndexOutOfBoundsException e) { - } - - try { - Collections.swap(smallList, 6, -1); - fail("Expected IndexOutOfBoundsException for -1"); - } catch (IndexOutOfBoundsException e) { - } - - try { - Collections.swap(smallList, 6, 11); - fail("Expected IndexOutOfBoundsException for 11"); - } catch (IndexOutOfBoundsException e) { - } - - try { - Collections.swap(smallList, 11, 6); - fail("Expected IndexOutOfBoundsException for 11"); - } catch (IndexOutOfBoundsException e) { - } - - // Ensure a NPE is thrown if the list is NULL - try { - Collections.swap(null, 1, 1); - fail("Expected NullPointerException for null list parameter"); - } catch (NullPointerException e) { - } - - // test with valid parameters - Collections.swap(smallList, 4, 7); - assertEquals("Didn't Swap the element at position 4 ", new Integer(7), - smallList.get(4)); - assertEquals("Didn't Swap the element at position 7 ", new Integer(4), - smallList.get(7)); - - // make sure other elements didn't get swapped by mistake - for (int i = 0; i < 10; i++) { - if (i != 4 && i != 7) - assertEquals("shouldn't have swapped the element at position " - + i, new Integer(i), smallList.get(i)); - } - } - - /** - * java.util.Collections#replaceAll(java.util.List, java.lang.Object, - * java.lang.Object) - */ - public void test_replaceAllLjava_util_ListLjava_lang_ObjectLjava_lang_Object() { - // Test for method replaceAll(java.util.List, java.lang.Object, - // java.lang.Object) - - String string1 = "A-B-C-D-E-S-JF-SUB-G-H-I-J-SUBL-K-L-LIST-M-N--S-S-O-SUBLIS-P-Q-R-SUBLIST-S-T-U-V-W-X-Y-Z"; - char[] chars = string1.toCharArray(); - List list = new ArrayList(); - for (int i = 0; i < chars.length; i++) { - list.add(new Character(chars[i])); - } - - try { - Collections.replaceAll(null, new Object(), new Object()); - fail("Expected NullPointerException for null list parameter"); - } catch (NullPointerException e) { - } - - // test replace for an element that is not in the list - boolean result = Collections.replaceAll(list, new Character('1'), - new Character('Z')); - assertFalse("Test1: Collections.replaceAll() returned wrong result", - result); - assertEquals("Test2 : ReplaceAll modified the list incorrectly", - string1, getString(list)); - - // test replace for an element that is in the list - result = Collections.replaceAll(list, new Character('S'), - new Character('K')); - assertTrue("Test3: Collections.replaceAll() returned wrong result", - result); - assertEquals("Test4: ReplaceAll modified the list incorrectly", - (string1 = string1.replace('S', 'K')), getString(list)); - - // test replace for the last element in the list - result = Collections.replaceAll(list, new Character('Z'), - new Character('N')); - assertTrue("Test5: Collections.replaceAll() returned wrong result", - result); - assertEquals("Test6: ReplaceAll modified the list incorrectly", - (string1 = string1.replace('Z', 'N')), getString(list)); - - // test replace for the first element in the list - result = Collections.replaceAll(list, new Character('A'), - new Character('B')); - assertTrue("Test7: Collections.replaceAll() returned wrong result", - result); - assertEquals("Test8: ReplaceAll modified the list incorrectly", - (string1 = string1.replace('A', 'B')), getString(list)); - - // test replacing elements with null - LinkedList smallList = new LinkedList(); - for (int i = 0; i < 10; i++) { - smallList.add(objArray[i]); - } - smallList.set(4, new Integer(5)); - result = Collections.replaceAll(smallList, new Integer(5), null); - assertTrue("Test9: Collections.replaceAll() returned wrong result", - result); - for (int i = 0; i < smallList.size(); i++) { - if (i == 4 || i == 5) - assertSame("Test9: ReplaceAll didn't replace element at " + i, - null, smallList.get(i)); - else - assertEquals( - "Test9: ReplaceAll shouldn't have replaced element at " - + i, new Integer(i), smallList.get(i)); - } - - // test replacing null elements with another value - result = Collections.replaceAll(smallList, null, new Integer(99)); - assertTrue("Test10: Collections.replaceAll() returned wrong result", - result); - - for (int i = 0; i < smallList.size(); i++) { - if (i == 4 || i == 5) - assertEquals("Test10: ReplaceAll didn't replace element at " - + i, new Integer(99), smallList.get(i)); - else - assertEquals( - "Test10: ReplaceAll shouldn't have replaced element at " - + i, new Integer(i), smallList.get(i)); - } - - Mock_ArrayList mal = new Mock_ArrayList(); - - mal.add("First"); - mal.add("Second"); - - try { - Collections.replaceAll(mal, "Second", null); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException e) { - //expected - } - } - - /** - * java.util.Collections#rotate(java.util.List, int) - */ - public void test_rotateLjava_util_ListI() { - // Test for method rotate(java.util.List, int) - - try { - Collections.rotate(null, 0); - fail("Expected NullPointerException for null list parameter"); - } catch (NullPointerException e) { - } - - // Test rotating a Sequential Access List - LinkedList list1 = new LinkedList(); - for (int i = 0; i < 10; i++) { - list1.add(objArray[i]); - } - testRotate(list1, "Sequential Access"); - - // Test rotating a Random Access List - ArrayList list2 = new ArrayList(); - for (int i = 0; i < 10; i++) { - list2.add(objArray[i]); - } - testRotate(list2, "Random Access"); - } - - private void testRotate(List list, String type) { - // rotate with positive distance - Collections.rotate(list, 7); - assertEquals("Test1: rotate modified the " + type - + " list incorrectly,", "3456789012", getString(list)); - - // rotate with negative distance - Collections.rotate(list, -2); - assertEquals("Test2: rotate modified the " + type - + " list incorrectly,", "5678901234", getString(list)); - - // rotate sublist with negative distance - List subList = list.subList(1, 5); - Collections.rotate(subList, -1); - assertEquals("Test3: rotate modified the " + type - + " list incorrectly,", "5789601234", getString(list)); - - // rotate sublist with positive distance - Collections.rotate(subList, 2); - assertEquals("Test4: rotate modified the " + type - + " list incorrectly,", "5967801234", getString(list)); - - // rotate with positive distance that is larger than list size - Collections.rotate(list, 23); - assertEquals("Test5: rotate modified the " + type - + " list incorrectly,", "2345967801", getString(list)); - - // rotate with negative distance that is larger than list size - Collections.rotate(list, -23); - assertEquals("Test6: rotate modified the " + type - + " list incorrectly,", "5967801234", getString(list)); - - // rotate with 0 and equivalent distances, this should make no - // modifications to the list - Collections.rotate(list, 0); - assertEquals("Test7: rotate modified the " + type - + " list incorrectly,", "5967801234", getString(list)); - - Collections.rotate(list, -30); - assertEquals("Test8: rotate modified the " + type - + " list incorrectly,", "5967801234", getString(list)); - - Collections.rotate(list, 30); - assertEquals("Test9: rotate modified the " + type - + " list incorrectly,", "5967801234", getString(list)); - } - - private String getString(List list) { - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < list.size(); i++) { - buffer.append(list.get(i)); - } - return buffer.toString(); - } - - /** - * java.util.Collections#rotate(java.util.List, int) - */ - public void test_rotate2() { - List list = new ArrayList(); - try { - Collections.rotate(list, 5); - } catch (UnsupportedOperationException e) { - fail("Unexpected UnsupportedOperationException for empty list, " - + e); - } - - list.add(0, "zero"); - list.add(1, "one"); - list.add(2, "two"); - list.add(3, "three"); - list.add(4, "four"); - - Collections.rotate(list, Integer.MIN_VALUE); - assertEquals("Rotated incorrectly at position 0, ", "three", - (String) list.get(0)); - assertEquals("Rotated incorrectly at position 1, ", "four", - (String) list.get(1)); - assertEquals("Rotated incorrectly at position 2, ", "zero", - (String) list.get(2)); - assertEquals("Rotated incorrectly at position 3, ", "one", - (String) list.get(3)); - assertEquals("Rotated incorrectly at position 4, ", "two", - (String) list.get(4)); - } - - /** - * java.util.Collections#indexOfSubList(java.util.List, - * java.util.List) - */ - public void test_indexOfSubListLjava_util_ListLjava_util_List() { - // Test for method int indexOfSubList(java.util.List, java.util.List) - List list = new ArrayList(); - try { - Collections.indexOfSubList(null, list); - fail("Expected NullPointerException for null list first parameter"); - } catch (NullPointerException e) { - } - try { - Collections.indexOfSubList(list, null); - fail("Expected NullPointerException for null list second parameter"); - } catch (NullPointerException e) { - } - - String string1 = "A-B-C-D-E-S-JF-SUB-G-H-I-J-SUBL-K-L-LIST-M-N--S-S-O-SUBLIS-P-Q-R-SUBLIST-S-T-U-V-W-X-Y-Z"; - - testwithCharList(1, string1, "B", true); - testwithCharList(2, string1, "LIST", true); - testwithCharList(3, string1, "SUBLIST", true); - testwithCharList(4, string1, "NONE", true); - testwithCharList(5, string1, "END", true); - - // test boundary conditions: - testwithCharList(6, "", "", true); - testwithCharList(7, "LIST", "", true); - testwithCharList(8, "", "SUBLIST", true); - } - - /** - * java.util.Collections#indexOfSubList(java.util.List, - * java.util.List) - */ - public void test_indexOfSubList2() { - ArrayList sub = new ArrayList(); - sub.add(new Integer(1)); - sub.add(new Integer(2)); - sub.add(new Integer(3)); - - ArrayList sub2 = new ArrayList(); - sub2.add(new Integer(7)); - sub2.add(new Integer(8)); - - ArrayList src = new ArrayList(); - src.addAll(sub); - src.addAll(sub); - src.addAll(sub); - src.add(new Integer(5)); - src.add(new Integer(6)); - - // so src becomes a list like this: - // [1, 2, 3, 1, 2, 3, 1, 2, 3, 5, 6] - - sub = new ArrayList(src.subList(3, 11)); - // [1, 2, 3, 1, 2, 3, 5, 6] - assertEquals("TestA : Returned wrong indexOfSubList, ", 3, Collections - .indexOfSubList(src, sub)); - - sub = new ArrayList(src.subList(6, 11)); - // [1, 2, 3, 5, 6] - assertEquals("TestB : Returned wrong indexOfSubList, ", 6, Collections - .indexOfSubList(src, sub)); - - sub = new ArrayList(src.subList(0, 3)); - // [1, 2, 3] - assertEquals("TestCC : Returned wrong indexOfSubList, ", 0, Collections - .indexOfSubList(src, sub)); - - sub = new ArrayList(src.subList(9, 11)); - // [5, 6] - assertEquals("TestD : Returned wrong indexOfSubList, ", 9, Collections - .indexOfSubList(src, sub)); - - sub = new ArrayList(src.subList(10, 11)); - // [6] - assertEquals("TestE : Returned wrong indexOfSubList, ", 10, Collections - .indexOfSubList(src, sub)); - - sub = new ArrayList(src.subList(0, 11)); - // the whole list - assertEquals("TestH : Returned wrong indexIndexOfSubList, ", 0, - Collections.indexOfSubList(src, sub)); - - // a non-matching list - assertEquals("TestI : Returned wrong indexOfSubList, ", -1, Collections - .indexOfSubList(src, sub2)); - } - - - private void testwithCharList(int count, String string1, String string2, - boolean first) { - char[] chars = string1.toCharArray(); - List list = new ArrayList(); - for (int i = 0; i < chars.length; i++) { - list.add(new Character(chars[i])); - } - chars = string2.toCharArray(); - List sublist = new ArrayList(); - for (int i = 0; i < chars.length; i++) { - sublist.add(new Character(chars[i])); - } - - if (first) - assertEquals("Test " + count + ": Returned wrong index:", string1 - .indexOf(string2), Collections - .indexOfSubList(list, sublist)); - else - assertEquals("Test " + count + ": Returned wrong index:", string1 - .lastIndexOf(string2), Collections.lastIndexOfSubList(list, - sublist)); - } - - /** - * java.util.Collections#lastIndexOfSubList(java.util.List, - * java.util.List) - */ - public void test_lastIndexOfSubListLjava_util_ListLjava_util_List() { - // Test for method int lastIndexOfSubList(java.util.List, - // java.util.List) - String string1 = "A-B-C-D-E-S-JF-SUB-G-H-I-J-SUBL-K-L-LIST-M-N--S-S-O-SUBLIS-P-Q-R-SUBLIST-S-T-U-V-W-X-Y-Z-END"; - - List list = new ArrayList(); - try { - Collections.lastIndexOfSubList(null, list); - fail("Expected NullPointerException for null list first parameter"); - } catch (NullPointerException e) { - } - try { - Collections.lastIndexOfSubList(list, null); - fail("Expected NullPointerException for null list second parameter"); - } catch (NullPointerException e) { - } - - testwithCharList(1, string1, "B", false); - testwithCharList(2, string1, "LIST", false); - testwithCharList(3, string1, "SUBLIST", false); - testwithCharList(4, string1, "END", false); - testwithCharList(5, string1, "NONE", false); - - // test boundary conditions - testwithCharList(6, "", "", false); - testwithCharList(7, "LIST", "", false); - testwithCharList(8, "", "SUBLIST", false); - } - - /** - * java.util.Collections#lastIndexOfSubList(java.util.List, - * java.util.List) - */ - public void test_lastIndexOfSubList2() { - ArrayList sub = new ArrayList(); - sub.add(new Integer(1)); - sub.add(new Integer(2)); - sub.add(new Integer(3)); - - ArrayList sub2 = new ArrayList(); - sub2.add(new Integer(7)); - sub2.add(new Integer(8)); - - ArrayList src = new ArrayList(); - src.addAll(sub); - src.addAll(sub); - src.addAll(sub); - src.add(new Integer(5)); - src.add(new Integer(6)); - - // so src is a list like this: - // [1, 2, 3, 1, 2, 3, 1, 2, 3, 5, 6] - - Collections.reverse(src); - // it becomes like this : - // [6, 5, 3, 2, 1, 3, 2, 1, 3, 2, 1] - - sub = new ArrayList(src.subList(0, 8)); - // [6, 5, 3, 2, 1, 3, 2, 1] - assertEquals("TestA : Returned wrong lastIndexOfSubList, ", 0, - Collections.lastIndexOfSubList(src, sub)); - - sub = new ArrayList(src.subList(0, 5)); - // [6, 5, 3, 2, 1] - assertEquals("TestB : Returned wrong lastIndexOfSubList, ", 0, - Collections.lastIndexOfSubList(src, sub)); - - sub = new ArrayList(src.subList(2, 5)); - // [3, 2, 1] - assertEquals("TestC : Returned wrong lastIndexOfSubList, ", 8, - Collections.lastIndexOfSubList(src, sub)); - - sub = new ArrayList(src.subList(9, 11)); - // [2, 1] - assertEquals("TestD : Returned wrong lastIndexOfSubList, ", 9, - Collections.lastIndexOfSubList(src, sub)); - - sub = new ArrayList(src.subList(10, 11)); - // [1] - assertEquals("TestE : Returned wrong lastIndexOfSubList, ", 10, - Collections.lastIndexOfSubList(src, sub)); - - sub = new ArrayList(src.subList(0, 2)); - // [6, 5] - assertEquals("TestF : Returned wrong lastIndexOfSubList, ", 0, - Collections.lastIndexOfSubList(src, sub)); - - sub = new ArrayList(src.subList(0, 1)); - // [6] - assertEquals("TestG : Returned wrong lastIndexOfSubList, ", 0, - Collections.lastIndexOfSubList(src, sub)); - - sub = new ArrayList(src.subList(0, 11)); - // the whole list - assertEquals("TestH : Returned wrong lastIndexOfSubList, ", 0, - Collections.lastIndexOfSubList(src, sub)); - - // a non-matching list - assertEquals("TestI : Returned wrong lastIndexOfSubList, ", -1, - Collections.lastIndexOfSubList(src, sub2)); - } - - /** - * java.util.Collections#list(java.util.Enumeration) - */ - public void test_listLjava_util_Enumeration() { - // Test for method java.util.ArrayList list(java.util.Enumeration) - - Enumeration e = Collections.enumeration(ll); - ArrayList al = Collections.list(e); - - int size = al.size(); - assertEquals("Wrong size", ll.size(), size); - - for (int i = 0; i < size; i++) { - assertEquals("wrong element at position " + i + ",", ll.get(i), al - .get(i)); - } - } - - /** - * java.util.Collections#synchronizedCollection(java.util.Collection) - */ - public void test_synchronizedCollectionLjava_util_Collection() { - // Test for method java.util.Collection - // java.util.Collections.synchronizedCollection(java.util.Collection) - - LinkedList smallList = new LinkedList(); - for (int i = 0; i < 50; i++) { - smallList.add(objArray[i]); - } - - final int numberOfLoops = 200; - Collection synchCol = Collections.synchronizedCollection(smallList); - // Replacing the previous line with the line below *should* cause the - // test to fail--the collecion below isn't synchronized - // Collection synchCol = smallList; - - SynchCollectionChecker normalSynchChecker = new SynchCollectionChecker( - synchCol, false, numberOfLoops); - SynchCollectionChecker offsetSynchChecker = new SynchCollectionChecker( - synchCol, true, numberOfLoops); - Thread normalThread = new Thread(normalSynchChecker); - Thread offsetThread = new Thread(offsetSynchChecker); - normalThread.start(); - offsetThread.start(); - while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops) - || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) { - try { - Thread.sleep(10); - } catch (InterruptedException e) { - } - } - assertTrue("Returned collection corrupted by multiple thread access", - normalSynchChecker.getResult() - && offsetSynchChecker.getResult()); - try { - normalThread.join(5000); - offsetThread.join(5000); - } catch (InterruptedException e) { - fail("join() interrupted"); - } - - synchCol.add(null); - assertTrue("Trying to use nulls in collection failed", synchCol - .contains(null)); - - smallList = new LinkedList(); - for (int i = 0; i < 100; i++) { - smallList.add(objArray[i]); - } - new Support_CollectionTest("", Collections - .synchronizedCollection(smallList)).runTest(); - } - - /** - * java.util.Collections#synchronizedList(java.util.List) - */ - public void test_synchronizedListLjava_util_List() { - try { - Collections.synchronizedList(null); - fail("Expected NullPointerException for null list parameter"); - } catch (NullPointerException e) { - } - - // test with a Sequential Access List - List smallList = new LinkedList(); - testSynchronizedList(smallList, "Sequential Access"); - - smallList = new LinkedList(); - List myList; - for (int i = 0; i < 100; i++) { - smallList.add(objArray[i]); - } - myList = Collections.synchronizedList(smallList); - new Support_ListTest("", myList).runTest(); - - // test with a Random Access List - smallList = new ArrayList(); - testSynchronizedList(smallList, "Random Access"); - - smallList = new ArrayList(); - for (int i = 0; i < 100; i++) { - smallList.add(objArray[i]); - } - myList = Collections.synchronizedList(smallList); - new Support_ListTest("", myList).runTest(); - } - - private void testSynchronizedList(List smallList, String type) { - for (int i = 0; i < 50; i++) { - smallList.add(objArray[i]); - } - final int numberOfLoops = 200; - List synchList = Collections.synchronizedList(smallList); - if (type.equals("Random Access")) - assertTrue( - "Returned synchronized list should implement the Random Access interface", - synchList instanceof RandomAccess); - else - assertTrue( - "Returned synchronized list should not implement the Random Access interface", - !(synchList instanceof RandomAccess)); - - // Replacing the previous line with the line below *should* cause the - // test to fail--the list below isn't synchronized - // List synchList = smallList; - SynchCollectionChecker normalSynchChecker = new SynchCollectionChecker( - synchList, false, numberOfLoops); - SynchCollectionChecker offsetSynchChecker = new SynchCollectionChecker( - synchList, true, numberOfLoops); - Thread normalThread = new Thread(normalSynchChecker); - Thread offsetThread = new Thread(offsetSynchChecker); - normalThread.start(); - offsetThread.start(); - while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops) - || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) { - try { - Thread.sleep(10); - } catch (InterruptedException e) { - } - } - assertTrue( - type - + " list tests: Returned list corrupted by multiple thread access", - normalSynchChecker.getResult() - && offsetSynchChecker.getResult()); - try { - normalThread.join(5000); - offsetThread.join(5000); - } catch (InterruptedException e) { - fail(type + " list tests: join() interrupted"); - } - synchList.set(25, null); - assertNull(type + " list tests: Trying to use nulls in list failed", - synchList.get(25)); - } - - /** - * java.util.Collections#synchronizedMap(java.util.Map) - */ - public void test_synchronizedMapLjava_util_Map() { - // Test for method java.util.Map - // java.util.Collections.synchronizedMap(java.util.Map) - HashMap smallMap = new HashMap(); - for (int i = 0; i < 50; i++) { - smallMap.put(objArray[i], objArray[i]); - } - - final int numberOfLoops = 200; - Map synchMap = Collections.synchronizedMap(smallMap); - // Replacing the previous line with the line below should cause the test - // to fail--the list below isn't synchronized - // Map synchMap = smallMap; - - SynchMapChecker normalSynchChecker = new SynchMapChecker(synchMap, - false, numberOfLoops); - SynchMapChecker offsetSynchChecker = new SynchMapChecker(synchMap, - true, numberOfLoops); - Thread normalThread = new Thread(normalSynchChecker); - Thread offsetThread = new Thread(offsetSynchChecker); - normalThread.start(); - offsetThread.start(); - while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops) - || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) { - try { - Thread.sleep(10); - } catch (InterruptedException e) { - } - } - assertTrue("Returned map corrupted by multiple thread access", - normalSynchChecker.getResult() - && offsetSynchChecker.getResult()); - try { - normalThread.join(5000); - offsetThread.join(5000); - } catch (InterruptedException e) { - fail("join() interrupted"); - } - - // synchronized map does not have to permit null keys or values - synchMap.put(new Long(25), null); - synchMap.put(null, new Long(30)); - assertNull("Trying to use a null value in map failed", synchMap - .get(new Long(25))); - assertTrue("Trying to use a null key in map failed", synchMap.get(null) - .equals(new Long(30))); - - smallMap = new HashMap(); - for (int i = 0; i < 100; i++) { - smallMap.put(objArray[i].toString(), objArray[i]); - } - synchMap = Collections.synchronizedMap(smallMap); - new Support_UnmodifiableMapTest("", synchMap).runTest(); - synchMap.keySet().remove(objArray[50].toString()); - assertNull( - "Removing a key from the keySet of the synchronized map did not remove it from the synchronized map: ", - synchMap.get(objArray[50].toString())); - assertNull( - "Removing a key from the keySet of the synchronized map did not remove it from the original map", - smallMap.get(objArray[50].toString())); - } - - /** - * java.util.Collections#synchronizedSet(java.util.Set) - */ - public void test_synchronizedSetLjava_util_Set() { - // Test for method java.util.Set - // java.util.Collections.synchronizedSet(java.util.Set) - HashSet smallSet = new HashSet(); - for (int i = 0; i < 50; i++) { - smallSet.add(objArray[i]); - } - - final int numberOfLoops = 200; - Set synchSet = Collections.synchronizedSet(smallSet); - // Replacing the previous line with the line below should cause the test - // to fail--the set below isn't synchronized - // Set synchSet = smallSet; - - SynchCollectionChecker normalSynchChecker = new SynchCollectionChecker( - synchSet, false, numberOfLoops); - SynchCollectionChecker offsetSynchChecker = new SynchCollectionChecker( - synchSet, true, numberOfLoops); - Thread normalThread = new Thread(normalSynchChecker); - Thread offsetThread = new Thread(offsetSynchChecker); - normalThread.start(); - offsetThread.start(); - while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops) - || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) { - try { - Thread.sleep(10); - } catch (InterruptedException e) { - } - } - assertTrue("Returned set corrupted by multiple thread access", - normalSynchChecker.getResult() - && offsetSynchChecker.getResult()); - try { - normalThread.join(5000); - offsetThread.join(5000); - } catch (InterruptedException e) { - fail("join() interrupted"); - } - - Set mySet = Collections.synchronizedSet(smallSet); - mySet.add(null); - assertTrue("Trying to use nulls in list failed", mySet.contains(null)); - - smallSet = new HashSet(); - for (int i = 0; i < 100; i++) { - smallSet.add(objArray[i]); - } - new Support_SetTest("", Collections.synchronizedSet(smallSet)) - .runTest(); - } - - /** - * java.util.Collections#synchronizedSortedMap(java.util.SortedMap) - */ - public void test_synchronizedSortedMapLjava_util_SortedMap() { - // Test for method java.util.SortedMap - // java.util.Collections.synchronizedSortedMap(java.util.SortedMap) - TreeMap smallMap = new TreeMap(); - for (int i = 0; i < 50; i++) { - smallMap.put(objArray[i], objArray[i]); - } - - final int numberOfLoops = 200; - Map synchMap = Collections.synchronizedMap(smallMap); - // Replacing the previous line with the line below should cause the test - // to fail--the list below isn't synchronized - // Map synchMap = smallMap; - - SynchMapChecker normalSynchChecker = new SynchMapChecker(synchMap, - false, numberOfLoops); - SynchMapChecker offsetSynchChecker = new SynchMapChecker(synchMap, - true, numberOfLoops); - Thread normalThread = new Thread(normalSynchChecker); - Thread offsetThread = new Thread(offsetSynchChecker); - normalThread.start(); - offsetThread.start(); - while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops) - || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) { - try { - Thread.sleep(10); - } catch (InterruptedException e) { - } - } - assertTrue("Returned map corrupted by multiple thread access", - normalSynchChecker.getResult() - && offsetSynchChecker.getResult()); - try { - normalThread.join(5000); - offsetThread.join(5000); - } catch (InterruptedException e) { - fail("join() interrupted"); - } - - smallMap = new TreeMap(); - for (int i = 0; i < 100; i++) { - smallMap.put(objArray[i].toString(), objArray[i]); - } - synchMap = Collections.synchronizedSortedMap(smallMap); - new Support_UnmodifiableMapTest("", synchMap).runTest(); - synchMap.keySet().remove(objArray[50].toString()); - assertNull( - "Removing a key from the keySet of the synchronized map did not remove it from the synchronized map", - synchMap.get(objArray[50].toString())); - assertNull( - "Removing a key from the keySet of the synchronized map did not remove it from the original map", - smallMap.get(objArray[50].toString())); - } - - /** - * java.util.Collections#synchronizedSortedSet(java.util.SortedSet) - */ - public void test_synchronizedSortedSetLjava_util_SortedSet() { - // Test for method java.util.SortedSet - // java.util.Collections.synchronizedSortedSet(java.util.SortedSet) - TreeSet smallSet = new TreeSet(); - for (int i = 0; i < 50; i++) { - smallSet.add(objArray[i]); - } - - final int numberOfLoops = 200; - Set synchSet = Collections.synchronizedSet(smallSet); - // Replacing the previous line with the line below should cause the test - // to fail--the list below isn't synchronized - // Set synchSet = smallSet; - - SynchCollectionChecker normalSynchChecker = new SynchCollectionChecker( - synchSet, false, numberOfLoops); - SynchCollectionChecker offsetSynchChecker = new SynchCollectionChecker( - synchSet, true, numberOfLoops); - Thread normalThread = new Thread(normalSynchChecker); - Thread offsetThread = new Thread(offsetSynchChecker); - normalThread.start(); - offsetThread.start(); - while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops) - || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) { - try { - Thread.sleep(10); - } catch (InterruptedException e) { - } - } - assertTrue("Returned set corrupted by multiple thread access", - normalSynchChecker.getResult() - && offsetSynchChecker.getResult()); - try { - normalThread.join(5000); - offsetThread.join(5000); - } catch (InterruptedException e) { - fail("join() interrupted"); - } - } - - /** - * java.util.Collections#unmodifiableCollection(java.util.Collection) - */ - public void test_unmodifiableCollectionLjava_util_Collection() { - // Test for method java.util.Collection - // java.util.Collections.unmodifiableCollection(java.util.Collection) - boolean exception = false; - Collection c = Collections.unmodifiableCollection(ll); - assertTrue("Returned collection is of incorrect size", c.size() == ll - .size()); - Iterator i = ll.iterator(); - while (i.hasNext()) - assertTrue("Returned list missing elements", c.contains(i.next())); - try { - c.add(new Object()); - } catch (UnsupportedOperationException e) { - exception = true; - // Correct - } - if (!exception) { - fail("Allowed modification of collection"); - } - - try { - c.remove(new Object()); - fail("Allowed modification of collection"); - } catch (UnsupportedOperationException e) { - // Correct - } - - Collection myCollection = new ArrayList(); - myCollection.add(new Integer(20)); - myCollection.add(null); - c = Collections.unmodifiableCollection(myCollection); - assertTrue("Collection should contain null", c.contains(null)); - assertTrue("Collection should contain Integer(20)", c - .contains(new Integer(20))); - - myCollection = new ArrayList(); - for (int counter = 0; counter < 100; counter++) { - myCollection.add(objArray[counter]); - } - new Support_UnmodifiableCollectionTest("", Collections - .unmodifiableCollection(myCollection)).runTest(); - } - - /** - * java.util.Collections#unmodifiableList(java.util.List) - */ - public void test_unmodifiableListLjava_util_List() { - // Test for method java.util.List - // java.util.Collections.unmodifiableList(java.util.List) - - // test with a Sequential Access List - boolean exception = false; - List c = Collections.unmodifiableList(ll); - // Ensure a NPE is thrown if the list is NULL - try { - Collections.unmodifiableList(null); - fail("Expected NullPointerException for null list parameter"); - } catch (NullPointerException e) { - } - - assertTrue("Returned list is of incorrect size", c.size() == ll.size()); - assertTrue( - "Returned List should not implement Random Access interface", - !(c instanceof RandomAccess)); - - Iterator i = ll.iterator(); - while (i.hasNext()) - assertTrue("Returned list missing elements", c.contains(i.next())); - try { - c.add(new Object()); - } catch (UnsupportedOperationException e) { - exception = true; - // Correct - } - if (!exception) { - fail("Allowed modification of list"); - } - - try { - c.remove(new Object()); - fail("Allowed modification of list"); - } catch (UnsupportedOperationException e) { - // Correct - } - - // test with a Random Access List - List smallList = new ArrayList(); - smallList.add(null); - smallList.add("yoink"); - c = Collections.unmodifiableList(smallList); - assertNull("First element should be null", c.get(0)); - assertTrue("List should contain null", c.contains(null)); - assertTrue( - "T1. Returned List should implement Random Access interface", - c instanceof RandomAccess); - - smallList = new ArrayList(); - for (int counter = 0; counter < 100; counter++) { - smallList.add(objArray[counter]); - } - List myList = Collections.unmodifiableList(smallList); - assertTrue("List should not contain null", !myList.contains(null)); - assertTrue( - "T2. Returned List should implement Random Access interface", - myList instanceof RandomAccess); - - assertTrue("get failed on unmodifiable list", myList.get(50).equals( - new Integer(50))); - ListIterator listIterator = myList.listIterator(); - for (int counter = 0; listIterator.hasNext(); counter++) { - assertTrue("List has wrong elements", ((Integer) listIterator - .next()).intValue() == counter); - } - new Support_UnmodifiableCollectionTest("", smallList).runTest(); - } - - /** - * java.util.Collections#unmodifiableMap(java.util.Map) - */ - public void test_unmodifiableMapLjava_util_Map() { - // Test for method java.util.Map - // java.util.Collections.unmodifiableMap(java.util.Map) - boolean exception = false; - Map c = Collections.unmodifiableMap(hm); - assertTrue("Returned map is of incorrect size", c.size() == hm.size()); - Iterator i = hm.keySet().iterator(); - while (i.hasNext()) { - Object x = i.next(); - assertTrue("Returned map missing elements", c.get(x).equals( - hm.get(x))); - } - try { - c.put(new Object(), ""); - } catch (UnsupportedOperationException e) { - exception = true; - // Correct - } - assertTrue("Allowed modification of map", exception); - - exception = false; - try { - c.remove(new Object()); - } catch (UnsupportedOperationException e) { - // Correct - exception = true; - } - assertTrue("Allowed modification of map", exception); - - exception = false; - Iterator it = c.entrySet().iterator(); - Map.Entry entry = (Map.Entry) it.next(); - try { - entry.setValue("modified"); - } catch (UnsupportedOperationException e) { - // Correct - exception = true; - } - assertTrue("Allowed modification of entry", exception); - - exception = false; - Object[] array = c.entrySet().toArray(); - try { - ((Map.Entry) array[0]).setValue("modified"); - } catch (UnsupportedOperationException e) { - // Correct - exception = true; - } - assertTrue("Allowed modification of array entry", exception); - - exception = false; - Map.Entry[] array2 = (Map.Entry[]) c.entrySet().toArray( - new Map.Entry[0]); - try { - array2[0].setValue("modified"); - } catch (UnsupportedOperationException e) { - // Correct - exception = true; - } - assertTrue("Allowed modification of array entry2", exception); - - HashMap smallMap = new HashMap(); - smallMap.put(null, new Long(30)); - smallMap.put(new Long(25), null); - Map unmodMap = Collections.unmodifiableMap(smallMap); - - assertNull("Trying to use a null value in map failed", unmodMap - .get(new Long(25))); - assertTrue("Trying to use a null key in map failed", unmodMap.get(null) - .equals(new Long(30))); - - smallMap = new HashMap(); - for (int counter = 0; counter < 100; counter++) { - smallMap.put(objArray[counter].toString(), objArray[counter]); - } - unmodMap = Collections.unmodifiableMap(smallMap); - new Support_UnmodifiableMapTest("", unmodMap).runTest(); - - } - - /** - * java.util.Collections#unmodifiableSet(java.util.Set) - */ - public void test_unmodifiableSetLjava_util_Set() { - // Test for method java.util.Set - // java.util.Collections.unmodifiableSet(java.util.Set) - boolean exception = false; - Set c = Collections.unmodifiableSet(s); - assertTrue("Returned set is of incorrect size", c.size() == s.size()); - Iterator i = ll.iterator(); - while (i.hasNext()) - assertTrue("Returned set missing elements", c.contains(i.next())); - try { - c.add(new Object()); - } catch (UnsupportedOperationException e) { - exception = true; - // Correct - } - if (!exception) { - fail("Allowed modification of set"); - } - try { - c.remove(new Object()); - fail("Allowed modification of set"); - } catch (UnsupportedOperationException e) { - // Correct - } - - Set mySet = Collections.unmodifiableSet(new HashSet()); - assertTrue("Should not contain null", !mySet.contains(null)); - mySet = Collections.unmodifiableSet(Collections.singleton(null)); - assertTrue("Should contain null", mySet.contains(null)); - - mySet = new TreeSet(); - for (int counter = 0; counter < 100; counter++) { - mySet.add(objArray[counter]); - } - new Support_UnmodifiableCollectionTest("", Collections - .unmodifiableSet(mySet)).runTest(); - } - - /** - * java.util.Collections#unmodifiableSortedMap(java.util.SortedMap) - */ - public void test_unmodifiableSortedMapLjava_util_SortedMap() { - // Test for method java.util.SortedMap - // java.util.Collections.unmodifiableSortedMap(java.util.SortedMap) - boolean exception = false; - TreeMap tm = new TreeMap(); - tm.putAll(hm); - Map c = Collections.unmodifiableSortedMap(tm); - assertTrue("Returned map is of incorrect size", c.size() == tm.size()); - Iterator i = hm.keySet().iterator(); - while (i.hasNext()) { - Object x = i.next(); - assertTrue("Returned map missing elements", c.get(x).equals( - tm.get(x))); - } - try { - c.put(new Object(), ""); - } catch (UnsupportedOperationException e) { - exception = true; - // Correct - } - - if (!exception) { - fail("Allowed modification of map"); - } - try { - c.remove(new Object()); - } catch (UnsupportedOperationException e) { - // Correct - return; - } - fail("Allowed modification of map"); - } - - /** - * java.util.Collections#unmodifiableSortedSet(java.util.SortedSet) - */ - public void test_unmodifiableSortedSetLjava_util_SortedSet() { - // Test for method java.util.SortedSet - // java.util.Collections.unmodifiableSortedSet(java.util.SortedSet) - boolean exception = false; - SortedSet ss = new TreeSet(); - ss.addAll(s); - SortedSet c = Collections.unmodifiableSortedSet(ss); - assertTrue("Returned set is of incorrect size", c.size() == ss.size()); - Iterator i = ll.iterator(); - while (i.hasNext()) - assertTrue("Returned set missing elements", c.contains(i.next())); - try { - c.add(new Object()); - } catch (UnsupportedOperationException e) { - exception = true; - // Correct - } - if (!exception) { - fail("Allowed modification of set"); - } - try { - c.remove(new Object()); - } catch (UnsupportedOperationException e) { - // Correct - return; - } - fail("Allowed modification of set"); - } - - /** - * Test unmodifiable objects toString methods - */ - public void test_unmodifiable_toString_methods() { - // Regression for HARMONY-552 - ArrayList al = new ArrayList(); - al.add("a"); - al.add("b"); - Collection uc = Collections.unmodifiableCollection(al); - assertEquals("[a, b]", uc.toString()); - HashMap m = new HashMap(); - m.put("one", "1"); - m.put("two", "2"); - Map um = Collections.unmodifiableMap(m); - assertTrue("{one=1, two=2}".equals(um.toString()) || - "{two=2, one=1}".equals(um.toString())); - } - - - public void test_singletonListLjava_lang_Object() { - // Test for method java.util.Set - // java.util.Collections.singleton(java.lang.Object) - String str = "Singleton"; - - List single = Collections.singletonList(str); - assertEquals(1, single.size()); - assertTrue(single.contains(str)); - assertFalse(single.contains(null)); - assertFalse(Collections.singletonList(null).contains(str)); - assertTrue(Collections.singletonList(null).contains(null)); - - try { - single.add("New element"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException e) { - //expected - } - } - - public void test_singletonMapLjava_lang_Object() { - // Test for method java.util.Set - // java.util.Collections.singleton(java.lang.Object) - Double key = new Double (3.14); - String value = "Fundamental constant"; - - Map single = Collections.singletonMap(key, value); - assertEquals(1, single.size()); - assertTrue(single.containsKey(key)); - assertTrue(single.containsValue(value)); - assertFalse(single.containsKey(null)); - assertFalse(single.containsValue(null)); - assertFalse(Collections.singletonMap(null, null).containsKey(key)); - assertFalse(Collections.singletonMap(null, null).containsValue(value)); - assertTrue(Collections.singletonMap(null, null).containsKey(null)); - assertTrue(Collections.singletonMap(null, null).containsValue(null)); - - try { - single.clear(); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException e) { - //expected - } - - try { - single.put(new Double(1), "one wrong value"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException e) { - //expected - } - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - objArray = new Object[1000]; - myobjArray = new Object[1000]; - for (int i = 0; i < objArray.length; i++) { - objArray[i] = new Integer(i); - myobjArray[i] = new MyInt(i); - } - - ll = new LinkedList(); - myll = new LinkedList(); - s = new HashSet(); - mys = new HashSet(); - reversedLinkedList = new LinkedList(); // to be sorted in reverse order - myReversedLinkedList = new LinkedList(); // to be sorted in reverse - // order - hm = new HashMap(); - for (int i = 0; i < objArray.length; i++) { - ll.add(objArray[i]); - myll.add(myobjArray[i]); - s.add(objArray[i]); - mys.add(myobjArray[i]); - reversedLinkedList.add(objArray[objArray.length - i - 1]); - myReversedLinkedList.add(myobjArray[myobjArray.length - i - 1]); - hm.put(objArray[i].toString(), objArray[i]); - } - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - objArray = null; - myobjArray = null; - - ll = null; - myll = null; - reversedLinkedList = null; - myReversedLinkedList = null; - s = null; - mys = null; - hm = null; - } - - protected void doneSuite() { - objArray = null; - } -} diff --git a/luni/src/test/java/tests/api/java/util/ConcurrentModTest.java b/luni/src/test/java/tests/api/java/util/ConcurrentModTest.java deleted file mode 100644 index 3750e81..0000000 --- a/luni/src/test/java/tests/api/java/util/ConcurrentModTest.java +++ /dev/null @@ -1,667 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.AbstractList; -import java.util.ArrayList; -import java.util.Collection; -import java.util.ConcurrentModificationException; -import java.util.List; -import java.util.Vector; - -import junit.framework.TestCase; - -public class ConcurrentModTest extends TestCase { - - /* - * Test method for 'java.util.AbstractList.subList(int, int)' - */ - public void testGet() { - AbstractList al = new ArrayList(); - Double one = new Double(1.0); - Double two = new Double(2.0); - Double three = new Double(3.0); - Double four = new Double(4.0); - al.add(one); - al.add(two); - al.add(three); - al.add(four); - List sub = al.subList(1, 3); - assertEquals(2, sub.size()); - // the sub.get(1) is 3.0 - assertTrue(((Double) sub.get(1)).doubleValue() <= 3.0); - assertTrue(((Double) sub.get(1)).doubleValue() > 2.0); - - al.remove(1); // remove the 2.0 - - try { - // illegal call the subList's method get(int). - sub.get(1); - fail("It should throws ConcurrentModificationException."); - } catch (ConcurrentModificationException e) { - return; - } - - try { - al.get(-1); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException ee) { - //expected - } - - try { - al.get(al.size()+1); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException ee) { - //expected - } - } - - /* - * Test method for 'java.util.AbstractList.subList(int, int)' - */ - public void testSet() { - AbstractList al = new ArrayList(); - Double one = new Double(1.0); - Double two = new Double(2.0); - Double three = new Double(3.0); - Double four = new Double(4.0); - al.add(one); - al.add(two); - al.add(three); - al.add(four); - List sub = al.subList(1, 3); - assertEquals(2, sub.size()); - // the sub.get(1) is 3.0 - assertTrue(((Double) sub.get(1)).doubleValue() <= 3.0); - assertTrue(((Double) sub.get(1)).doubleValue() > 2.0); - - al.remove(1); // remove the 2.0 - - try { - // illegal call the subList's method set(int,Object). - sub.set(1, two); - fail("It should throws ConcurrentModificationException."); - } catch (ConcurrentModificationException e) { - return; - } - } - - /* - * Test method for 'java.util.AbstractList.subList(int, int)' - */ - public void testAdd() { - AbstractList al = new ArrayList(); - Double one = new Double(1.0); - Double two = new Double(2.0); - Double three = new Double(3.0); - Double four = new Double(4.0); - al.add(one); - al.add(two); - al.add(three); - al.add(four); - List sub = al.subList(1, 3); - assertEquals(2, sub.size()); - // the sub.get(1) is 3.0 - assertTrue(((Double) sub.get(1)).doubleValue() <= 3.0); - assertTrue(((Double) sub.get(1)).doubleValue() > 2.0); - - al.remove(1); // remove the 2.0 - - try { - // illegal call the subList's method Add(int,Object). - sub.add(1, two); - fail("It should throws ConcurrentModificationException."); - } catch (ConcurrentModificationException e) { - return; - } - } - - /* - * Test method for 'java.util.AbstractList.subList(int, int)' - */ - public void testRemove() { - AbstractList al = new ArrayList(); - Double one = new Double(1.0); - Double two = new Double(2.0); - Double three = new Double(3.0); - Double four = new Double(4.0); - al.add(one); - al.add(two); - al.add(three); - al.add(four); - List sub = al.subList(1, 3); - assertEquals(2, sub.size()); - // the sub.get(1) is 3.0 - assertTrue(((Double) sub.get(1)).doubleValue() <= 3.0); - assertTrue(((Double) sub.get(1)).doubleValue() > 2.0); - - al.remove(1); // remove the 2.0 - - try { - // illegal call the subList's method remove(int). - sub.remove(1); - fail("It should throws ConcurrentModificationException."); - } catch (ConcurrentModificationException e) { - return; - } - - try { - sub.remove(-1); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException ee) { - //expected - } - - try { - sub.remove(sub.size() + 1); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException ee) { - //expected - } - - al = new AbstractList() { - - @Override - public Object get(int index) { - // TODO Auto-generated method stub - return null; - } - - @Override - public int size() { - // TODO Auto-generated method stub - return 0; - } - }; - - try { - al.remove(1); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException ee) { - //expected - } - } - - /* - * Test method for 'java.util.AbstractList.subList(int, int)' - */ - public void testAddAll() { - AbstractList al = new ArrayList(); - Double one = new Double(1.0); - Double two = new Double(2.0); - Double three = new Double(3.0); - Double four = new Double(4.0); - al.add(one); - al.add(two); - al.add(three); - al.add(four); - List sub = al.subList(1, 3); - assertEquals(2, sub.size()); - // the sub.get(1) is 3.0 - assertTrue(((Double) sub.get(1)).doubleValue() <= 3.0); - assertTrue(((Double) sub.get(1)).doubleValue() > 2.0); - - al.remove(1); // remove the 2.0 - - try { - // illegal call the subList's method addAll(int,Collection). - Collection c = new Vector(); - Double five = new Double(5.0); - c.add(five); - sub.addAll(1, c); - fail("It should throws ConcurrentModificationException."); - } catch (ConcurrentModificationException e) { - return; - } - } - - public void test_addLjava_lang_Object() { - AbstractList abstr = new AbstractList() { - - @Override - public Object get(int arg0) { - return null; - } - - @Override - public int size() { - return 0; - } - - }; - - try { - abstr.add(null); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException e) { - //ecpected - } - abstr = new AbstractList<Double>() { - @Override - public boolean add(Double value) { - return true; - } - - @Override - public Double get(int index) { - return null; - } - - @Override - public int size() { - return 0; - } - }; - - try { - abstr.add(1); - fail("ClassCastException expected"); - } catch (ClassCastException ee) { - //expected - } - - abstr = new AbstractList<Integer>() { - final int forbiddenValue = 33; - @Override - public boolean add(Integer value) { - if (value == forbiddenValue) { - throw new IllegalArgumentException(); - } - return true; - } - - @Override - public Integer get(int index) { - return null; - } - - @Override - public int size() { - return 0; - } - }; - - abstr.add(1); - try { - abstr.add(33); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException ee) { - //expected - } - } - - public void test_addILjava_lang_Object() { - AbstractList abstr = new AbstractList() { - - @Override - public Object get(int arg0) { - return null; - } - - @Override - public int size() { - return 0; - } - - }; - - try { - abstr.add(1, null); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException e) { - //ecpected - } - abstr = new AbstractList<Double>() { - @Override - public void add(int index, Double value) { - } - - @Override - public Double get(int index) { - return null; - } - - @Override - public int size() { - return 0; - } - }; - - try { - abstr.add(1, 1); - fail("ClassCastException expected"); - } catch (ClassCastException ee) { - //expected - } - - abstr = new AbstractList<Integer>() { - final int forbiddenValue = 33; - @Override - public void add(int index, Integer value) { - if (value == forbiddenValue) { - throw new IllegalArgumentException(); - } - } - - @Override - public Integer get(int index) { - return null; - } - - @Override - public int size() { - return 0; - } - }; - - abstr.add(1, 1); - try { - abstr.add(1, 33); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException ee) { - //expected - } - - abstr = new ArrayList(); - - abstr.add(0, "element"); - abstr.add(1, null); - abstr.add(2, 1); - abstr.add(3, new Double(33)); - - try { - abstr.add(-3, new Double(33)); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException ee) { - //expected - } - - try { - abstr.add(abstr.size() + 1, new Double(33)); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException ee) { - //expected - } - } - - public void test_addAllILjava_util_Collection() { - Collection c = new Vector(); - c.add(new Double(33)); - c.add(10); - c.add("String"); - - AbstractList abstr = new AbstractList() { - @Override - public Object get(int arg0) { - return null; - } - - @Override - public int size() { - return 0; - } - }; - - try { - abstr.addAll(0, null); - fail("NullPointerException expected"); - } catch (NullPointerException ee) { - //expected - } - - try { - abstr.addAll(0, c); - fail("UnsuportedOperationException expected"); - } catch (UnsupportedOperationException ee) { - //expected - } - - abstr = new AbstractList<Double>() { - @Override - public void add(int index, Double value) { - } - - @Override - public Double get(int arg0) { - return null; - } - - @Override - public int size() { - return 0; - } - }; - - try { - abstr.addAll(0, c); - fail("ClassCastException expected"); - } catch (ClassCastException ee) { - //expectd - } - - abstr = new AbstractList<Integer>() { - final int forbiddenValue = 33; - @Override - public void add(int index, Integer value) { - if (value == forbiddenValue) { - throw new IllegalArgumentException(); - } - } - - @Override - public Integer get(int arg0) { - return null; - } - - @Override - public int size() { - return 0; - } - }; - c.clear(); - c.add(new Integer(1)); - c.add(new Integer(2)); - c.add(new Integer(3)); - c.add(new Integer(4)); - c.add(new Integer(5)); - - abstr.addAll(0, c); - - c.add(new Integer(33)); - - try { - abstr.addAll(0, c); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException ee) { - //expected - } - abstr = new ArrayList(); - abstr.addAll(0, c); - - try { - abstr.addAll(-1, c); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException ee) { - //expected - } - - try { - abstr.addAll(abstr.size() + 1, c); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException ee) { - //expected - } - } - - public void test_clear() { - AbstractList abstr = new ArrayList(); - - assertEquals(0, abstr.size()); - abstr.add("String"); - abstr.add("1"); - abstr.add(2); - abstr.add(new Double(3)); - assertEquals(4, abstr.size()); - abstr.clear(); - assertEquals(0, abstr.size()); - } - - public void test_equalsLjava_lang_Object() { - Collection c = new Vector(); - c.add(new Double(33)); - c.add(10); - c.add("String"); - - AbstractList abstr = new ArrayList(); - AbstractList abstr1 = new ArrayList(); - - assertFalse(abstr.equals(this)); - abstr.add(new Double(33)); - abstr.add(10); - abstr.add("String"); - assertTrue(abstr.equals(c)); - abstr1.addAll(c); - assertTrue(abstr.equals(abstr1)); - } - - public void test_setILjava_lang_Object() { - Collection c = new Vector(); - c.add(new Double(33)); - c.add(10); - c.add("String"); - - AbstractList abstr1 = new ArrayList(); - AbstractList abstr2 = new ArrayList(); - - abstr1.addAll(c); - abstr2.addAll(c); - assertTrue(abstr1.equals(abstr2)); - abstr1.set(1, 1); - assertFalse(abstr1.equals(abstr2)); - - try { - abstr1.set(abstr1.size() + 1, 1); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException ee) { - //expected - } - - try { - abstr1.set(-1, 1); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException ee) { - //expected - } - - AbstractList abstr = new AbstractList() { - - @Override - public Object get(int index) { - return null; - } - - @Override - public int size() { - return 0; - } - - }; - - try { - abstr.set(0, null); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException ee) { - //expected - } - - abstr = new AbstractList<Double>() { - @Override - public Double set(int index, Double value) { - return value; - } - - @Override - public Double get(int index) { - return null; - } - - @Override - public int size() { - return 0; - } - }; - - try { - abstr.set(0, 1); - fail("ClassCastException expected"); - } catch (ClassCastException ee) { - //expected - } - - abstr = new AbstractList<Integer>() { - final int forbiddenValue = 33; - @Override - public Integer set(int index, Integer value) { - if (value == forbiddenValue) { - throw new IllegalArgumentException(); - } - return value; - } - - @Override - public Integer get(int index) { - return null; - } - - @Override - public int size() { - return 0; - } - }; - - try { - abstr.set(0, 33); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException ee) { - //expected - } - } - class Mock_ArrayList extends ArrayList { - @Override - public void removeRange(int fromIndex, int toIndex) { - super.removeRange(fromIndex, toIndex); - } - } - - public void test_removeRangeII() { - Mock_ArrayList al1 = new Mock_ArrayList(); - al1.add(1); - al1.add(2); - al1.add(3); - al1.add(4); - al1.add(5); - Mock_ArrayList al2 = new Mock_ArrayList(); - - al2.add(1); - al2.add(5); - assertNotSame(al1,al2); - al1.removeRange(1, 4); - assertEquals(al1,al2); - } -} diff --git a/luni/src/test/java/tests/api/java/util/ConcurrentModificationExceptionTest.java b/luni/src/test/java/tests/api/java/util/ConcurrentModificationExceptionTest.java deleted file mode 100644 index 0cd4076..0000000 --- a/luni/src/test/java/tests/api/java/util/ConcurrentModificationExceptionTest.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.Collection; -import java.util.ConcurrentModificationException; -import java.util.Iterator; -import java.util.LinkedList; - -public class ConcurrentModificationExceptionTest extends - junit.framework.TestCase { - - static public class CollectionModifier implements Runnable { - Collection col; - - boolean keepGoing = true; - - public CollectionModifier(Collection c) { - col = c; - } - - public void stopNow() { - keepGoing = false; - } - - public void run() { - Object someItem = new Integer(-1); - while (keepGoing) { - col.add(someItem); - col.remove(someItem); - } - } - } - - /** - * java.util.ConcurrentModificationException#ConcurrentModificationException() - */ - public void test_Constructor() { - // Test for method java.util.ConcurrentModificationException() - Collection myCollection = new LinkedList(); - Iterator myIterator = myCollection.iterator(); - for (int counter = 0; counter < 50; counter++) - myCollection.add(new Integer(counter)); - CollectionModifier cm = new CollectionModifier(myCollection); - Thread collectionSlapper = new Thread(cm); - try { - collectionSlapper.start(); - while (myIterator.hasNext()) - myIterator.next(); - } catch (ConcurrentModificationException e) { - cm.stopNow(); - return; - } - cm.stopNow(); - // The exception should have been thrown--if the code flow makes it here - // the test has failed - fail("Failed to throw expected ConcurrentModificationException"); - } - - /** - * java.util.ConcurrentModificationException#ConcurrentModificationException(java.lang.String) - */ - public void test_ConstructorLjava_lang_String() { - // Test for method - // java.util.ConcurrentModificationException(java.lang.String) - String errorMessage = "This is an error message"; - try { - // This is here to stop "unreachable code" unresolved problem - if (true) - throw new ConcurrentModificationException(errorMessage); - } catch (ConcurrentModificationException e) { - assertTrue("Exception thrown without error message", e.getMessage() - .equals(errorMessage)); - return; - } - fail("Failed to throw expected ConcurrentModificationException"); - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/util/CurrencyTest.java b/luni/src/test/java/tests/api/java/util/CurrencyTest.java deleted file mode 100644 index 82fd7cf..0000000 --- a/luni/src/test/java/tests/api/java/util/CurrencyTest.java +++ /dev/null @@ -1,428 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Currency; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Locale; -import java.util.Set; - -public class CurrencyTest extends junit.framework.TestCase { - - private static Locale defaultLocale = Locale.getDefault(); - - /** - * java.util.Currency#getInstance(java.lang.String) - */ - public void test_getInstanceLjava_lang_String() { - // see test_getInstanceLjava_util_Locale() tests - } - - /** - * java.util.Currency#getInstance(java.util.Locale) - */ - public void test_getInstanceLjava_util_Locale() { - /* - * the behaviour in all these three cases should be the same since this - * method ignores language and variant component of the locale. - */ - Currency c0 = Currency.getInstance("CAD"); - Currency c1 = Currency.getInstance(new Locale("en", "CA")); - assertTrue( - "Currency.getInstance(new Locale(\"en\",\"CA\")) isn't equal to Currency.getInstance(\"CAD\")", - c1 == c0); - Currency c2 = Currency.getInstance(new Locale("fr", "CA")); - assertTrue( - "Currency.getInstance(new Locale(\"fr\",\"CA\")) isn't equal to Currency.getInstance(\"CAD\")", - c2 == c0); - Currency c3 = Currency.getInstance(new Locale("", "CA")); - assertTrue( - "Currency.getInstance(new Locale(\"\",\"CA\")) isn't equal to Currency.getInstance(\"CAD\")", - c3 == c0); - - c0 = Currency.getInstance("JPY"); - c1 = Currency.getInstance(new Locale("ja", "JP")); - assertTrue( - "Currency.getInstance(new Locale(\"ja\",\"JP\")) isn't equal to Currency.getInstance(\"JPY\")", - c1 == c0); - c2 = Currency.getInstance(new Locale("", "JP")); - assertTrue( - "Currency.getInstance(new Locale(\"\",\"JP\")) isn't equal to Currency.getInstance(\"JPY\")", - c2 == c0); - c3 = Currency.getInstance(new Locale("bogus", "JP")); - assertTrue( - "Currency.getInstance(new Locale(\"bogus\",\"JP\")) isn't equal to Currency.getInstance(\"JPY\")", - c3 == c0); - - Locale localeGu = new Locale("gu", "IN"); - Currency cGu = Currency.getInstance(localeGu); - Locale localeKn = new Locale("kn", "IN"); - Currency cKn = Currency.getInstance(localeKn); - assertTrue("Currency.getInstance(Locale_" + localeGu.toString() + "))" - + "isn't equal to " + "Currency.getInstance(Locale_" - + localeKn.toString() + "))", cGu == cKn); - - // some teritories do not have currencies, like Antarctica - Locale loc = new Locale("", "AQ"); - try { - Currency curr = Currency.getInstance(loc); - assertNull( - "Currency.getInstance(new Locale(\"\", \"AQ\")) did not return null", - curr); - } catch (IllegalArgumentException e) { - fail("Unexpected IllegalArgumentException " + e); - } - - // unsupported/legacy iso3 countries - loc = new Locale("", "ZR"); - try { - Currency curr = Currency.getInstance(loc); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException e) { - } - - loc = new Locale("", "ZAR"); - try { - Currency curr = Currency.getInstance(loc); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException e) { - } - - loc = new Locale("", "FX"); - try { - Currency curr = Currency.getInstance(loc); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException e) { - } - - loc = new Locale("", "FXX"); - try { - Currency curr = Currency.getInstance(loc); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException e) { - } - } - - /** - * java.util.Currency#getSymbol() - */ - public void test_getSymbol() { - Currency currK = Currency.getInstance("KRW"); - Currency currI = Currency.getInstance("IEP"); - Currency currUS = Currency.getInstance("USD"); - - Locale.setDefault(Locale.US); - // BEGIN android-changed - // KRW currency symbol is \u20a9 since CLDR1.7 release. - assertEquals("currK.getSymbol()", "\u20a9", currK.getSymbol()); - // IEP currency symbol is IEP since CLDR2.0 release. - assertEquals("currI.getSymbol()", "IEP", currI.getSymbol()); - // END android-changed - assertEquals("currUS.getSymbol()", "$", currUS.getSymbol()); - - Locale.setDefault(new Locale("en", "IE")); - // BEGIN android-changed - assertEquals("currK.getSymbol()", "\u20a9", currK.getSymbol()); - assertEquals("currI.getSymbol()", "IEP", currI.getSymbol()); - assertEquals("currUS.getSymbol()", "$", currUS.getSymbol()); - // END android-changed - - // test what happens if this is an invalid locale, - // one with Korean country but an India language - Locale.setDefault(new Locale("kr", "KR")); - // BEGIN android-changed - assertEquals("currK.getSymbol()", "\u20a9", currK.getSymbol()); - assertEquals("currI.getSymbol()", "IEP", currI.getSymbol()); - // END android-changed - assertEquals("currUS.getSymbol()", "$", currUS.getSymbol()); - } - - /** - * java.util.Currency#getSymbol(java.util.Locale) - */ - public void test_getSymbolLjava_util_Locale() { - //Tests was simplified because java specification not - // includes strong requirements for returnig symbol. - // on android platform used wrong character for yen - // sign: \u00a5 instead of \uffe5 - Locale[] desiredLocales = new Locale[]{ - Locale.JAPAN, Locale.JAPANESE, - Locale.FRANCE, Locale.FRENCH, - Locale.US, Locale.UK, - Locale.CANADA, Locale.CANADA_FRENCH, - Locale.ENGLISH, - new Locale("ja", "JP"), new Locale("", "JP"), - - new Locale("fr", "FR"), new Locale("", "FR"), - - new Locale("en", "US"), new Locale("", "US"), - new Locale("es", "US"), new Locale("ar", "US"), - new Locale("ja", "US"), - - new Locale("en", "CA"), new Locale("fr", "CA"), - new Locale("", "CA"), new Locale("ar", "CA"), - - new Locale("ja", "JP"), new Locale("", "JP"), - new Locale("ar", "JP"), - - new Locale("ja", "AE"), new Locale("en", "AE"), - new Locale("ar", "AE"), - - new Locale("da", "DK"), new Locale("", "DK"), - - new Locale("da", ""), new Locale("ja", ""), - new Locale("en", "")}; - - Set<Locale> availableLocales = new HashSet<Locale>(Arrays.asList(Locale.getAvailableLocales())); - - ArrayList<Locale> locales = new ArrayList<Locale>(); - for (Locale desiredLocale : desiredLocales) { - if (availableLocales.contains(desiredLocale)) { - locales.add(desiredLocale); - } - } - - Locale[] loc1 = locales.toArray(new Locale[locales.size()]); - - String[] euro = new String[] {"EUR", "\u20ac"}; - // \u00a5 and \uffe5 are actually the same symbol, just different code points. - // But the RI returns the \uffe5 and Android returns those with \u00a5 - String[] yen = new String[] {"JPY", "\u00a5", "\u00a5JP", "JP\u00a5", "\uffe5", "\uffe5JP", "JP\uffe5"}; - String[] dollar = new String[] {"USD", "$", "US$", "$US"}; - // BEGIN android-changed - // Starting CLDR 1.7 release, currency symbol for CAD changed to CA$ in some locales such as ja. - String[] cDollar = new String[] {"CA$", "CAD", "$", "Can$", "$CA"}; - // END android-changed - - Currency currE = Currency.getInstance("EUR"); - Currency currJ = Currency.getInstance("JPY"); - Currency currUS = Currency.getInstance("USD"); - Currency currCA = Currency.getInstance("CAD"); - - int i, j, k; - boolean flag; - - for(k = 0; k < loc1.length; k++) { - Locale.setDefault(loc1[k]); - - for (i = 0; i < loc1.length; i++) { - flag = false; - for (j = 0; j < euro.length; j++) { - if (currE.getSymbol(loc1[i]).equals(euro[j])) { - flag = true; - break; - } - } - assertTrue("Default Locale is: " + Locale.getDefault() - + ". For locale " + loc1[i] - + " the Euro currency returned " - + currE.getSymbol(loc1[i]) - + ". Expected was one of these: " - + Arrays.toString(euro), flag); - } - - for (i = 0; i < loc1.length; i++) { - flag = false; - for (j = 0; j < yen.length; j++) { - byte[] b1 = null; - byte[] b2 = null; - if (currJ.getSymbol(loc1[i]).equals(yen[j])) { - flag = true; - break; - } - } - assertTrue("Default Locale is: " + Locale.getDefault() - + ". For locale " + loc1[i] - + " the Yen currency returned " - + currJ.getSymbol(loc1[i]) - + ". Expected was one of these: " - + Arrays.toString(yen), flag); - } - - for (i = 0; i < loc1.length; i++) { - flag = false; - for (j = 0; j < dollar.length; j++) { - if (currUS.getSymbol(loc1[i]).equals(dollar[j])) { - flag = true; - break; - } - } - assertTrue("Default Locale is: " + Locale.getDefault() - + ". For locale " + loc1[i] - + " the Dollar currency returned " - + currUS.getSymbol(loc1[i]) - + ". Expected was one of these: " - + Arrays.toString(dollar), flag); - } - - for (i = 0; i < loc1.length; i++) { - flag = false; - for (j = 0; j < cDollar.length; j++) { - if (currCA.getSymbol(loc1[i]).equals(cDollar[j])) { - flag = true; - break; - } - } - assertTrue("Default Locale is: " + Locale.getDefault() - + ". For locale " + loc1[i] - + " the Canadian Dollar currency returned " - + currCA.getSymbol(loc1[i]) - + ". Expected was one of these: " - + Arrays.toString(cDollar), flag); - } - } - } - - /** - * java.util.Currency#getDefaultFractionDigits() - */ - public void test_getDefaultFractionDigits() { - - Currency c1 = Currency.getInstance("TND"); - c1.getDefaultFractionDigits(); - assertEquals(" Currency.getInstance(\"" + c1 - + "\") returned incorrect number of digits. ", 3, c1 - .getDefaultFractionDigits()); - - Currency c2 = Currency.getInstance("EUR"); - c2.getDefaultFractionDigits(); - assertEquals(" Currency.getInstance(\"" + c2 - + "\") returned incorrect number of digits. ", 2, c2 - .getDefaultFractionDigits()); - - Currency c3 = Currency.getInstance("JPY"); - c3.getDefaultFractionDigits(); - assertEquals(" Currency.getInstance(\"" + c3 - + "\") returned incorrect number of digits. ", 0, c3 - .getDefaultFractionDigits()); - - Currency c4 = Currency.getInstance("XXX"); - c4.getDefaultFractionDigits(); - assertEquals(" Currency.getInstance(\"" + c4 - + "\") returned incorrect number of digits. ", -1, c4 - .getDefaultFractionDigits()); - } - - /** - * java.util.Currency#getCurrencyCode() Note: lines under remarks - * (Locale.CHINESE, Locale.ENGLISH, Locale.FRENCH, Locale.GERMAN, - * Locale.ITALIAN, Locale.JAPANESE, Locale.KOREAN) raises exception - * on SUN VM - */ - public void test_getCurrencyCode() { - final Collection<Locale> locVal = Arrays.asList( - Locale.CANADA, - Locale.CANADA_FRENCH, - Locale.CHINA, - // Locale.CHINESE, - // Locale.ENGLISH, - Locale.FRANCE, - // Locale.FRENCH, - // Locale.GERMAN, - Locale.GERMANY, - // Locale.ITALIAN, - Locale.ITALY, Locale.JAPAN, - // Locale.JAPANESE, - Locale.KOREA, - // Locale.KOREAN, - Locale.PRC, Locale.SIMPLIFIED_CHINESE, Locale.TAIWAN, Locale.TRADITIONAL_CHINESE, - Locale.UK, Locale.US); - final Collection<String> locDat = Arrays.asList("CAD", "CAD", "CNY", "EUR", "EUR", "EUR", - "JPY", "KRW", "CNY", "CNY", "TWD", "TWD", "GBP", "USD"); - - Iterator<String> dat = locDat.iterator(); - for (Locale l : locVal) { - String d = dat.next().trim(); - assertEquals("For locale " + l + " currency code wrong", Currency.getInstance(l) - .getCurrencyCode(), d); - } - } - - /** - * java.util.Currency#toString() Note: lines under remarks - * (Locale.CHINESE, Locale.ENGLISH, Locale.FRENCH, Locale.GERMAN, - * Locale.ITALIAN, Locale.JAPANESE, Locale.KOREAN) raises exception - * on SUN VM - */ - public void test_toString() { - final Collection<Locale> locVal = Arrays.asList( - Locale.CANADA, - Locale.CANADA_FRENCH, - Locale.CHINA, - // Locale.CHINESE, - // Locale.ENGLISH, - Locale.FRANCE, - // Locale.FRENCH, - // Locale.GERMAN, - Locale.GERMANY, - // Locale.ITALIAN, - Locale.ITALY, Locale.JAPAN, - // Locale.JAPANESE, - Locale.KOREA, - // Locale.KOREAN, - Locale.PRC, Locale.SIMPLIFIED_CHINESE, Locale.TAIWAN, Locale.TRADITIONAL_CHINESE, - Locale.UK, Locale.US); - final Collection<String> locDat = Arrays.asList("CAD", "CAD", "CNY", "EUR", "EUR", "EUR", - "JPY", "KRW", "CNY", "CNY", "TWD", "TWD", "GBP", "USD"); - - Iterator<String> dat = locDat.iterator(); - for (Locale l : locVal) { - String d = dat.next().trim(); - assertEquals("For locale " + l + " Currency.toString method returns wrong value", - Currency.getInstance(l).toString(), d); - } - } - - protected void setUp() { - Locale.setDefault(defaultLocale); - } - - protected void tearDown() { - } - - /** - * Helper method to display Currency info - * - * @param c - */ - private void printCurrency(Currency c) { - System.out.println(); - System.out.println(c.getCurrencyCode()); - System.out.println(c.getSymbol()); - System.out.println(c.getDefaultFractionDigits()); - } - - /** - * helper method to display Locale info - */ - private static void printLocale(Locale loc) { - System.out.println(); - System.out.println(loc.getDisplayName()); - System.out.println(loc.getCountry()); - System.out.println(loc.getLanguage()); - System.out.println(loc.getDisplayCountry()); - System.out.println(loc.getDisplayLanguage()); - System.out.println(loc.getDisplayName()); - System.out.println(loc.getISO3Country()); - System.out.println(loc.getISO3Language()); - } -} diff --git a/luni/src/test/java/tests/api/java/util/DateTest.java b/luni/src/test/java/tests/api/java/util/DateTest.java deleted file mode 100644 index 6100527..0000000 --- a/luni/src/test/java/tests/api/java/util/DateTest.java +++ /dev/null @@ -1,514 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.Locale; -import java.util.TimeZone; - -public class DateTest extends junit.framework.TestCase { - - /** - * java.util.Date#Date() - */ - public void test_Constructor() { - // Test for method java.util.Date() - GregorianCalendar gc = new GregorianCalendar(1998, Calendar.OCTOBER, - 13, 19, 9); - long oldTime = gc.getTime().getTime(); - long now = new Date().getTime(); - assertTrue("Created incorrect date: " + oldTime + " now: " + now, - oldTime < now); - } - - /** - * java.util.Date#Date(int, int, int) - */ - public void test_ConstructorIII() { - // Test for method java.util.Date(int, int, int) - Date d1 = new Date(70, 0, 1); // the epoch + local time - - // the epoch + local time - Date d2 = new Date(0 + d1.getTimezoneOffset() * 60 * 1000); - - assertTrue("Created incorrect date", d1.equals(d2)); - - Date date = new Date(99, 5, 22); - Calendar cal = new GregorianCalendar(1999, Calendar.JUNE, 22); - assertTrue("Wrong time zone", date.equals(cal.getTime())); - } - - /** - * java.util.Date#Date(int, int, int, int, int) - */ - public void test_ConstructorIIIII() { - // Test for method java.util.Date(int, int, int, int, int) - - // the epoch + local time + (1 hour and 1 minute) - Date d1 = new Date(70, 0, 1, 1, 1); - - // the epoch + local time + (1 hour and 1 minute) - Date d2 = new Date(0 + d1.getTimezoneOffset() * 60 * 1000 + 60 * 60 - * 1000 + 60 * 1000); - - assertTrue("Created incorrect date", d1.equals(d2)); - } - - /** - * java.util.Date#Date(int, int, int, int, int, int) - */ - public void test_ConstructorIIIIII() { - // Test for method java.util.Date(int, int, int, int, int, int) - - // the epoch + local time + (1 hour and 1 minute + 1 second) - Date d1 = new Date(70, 0, 1, 1, 1, 1); - - // the epoch + local time + (1 hour and 1 minute + 1 second) - Date d2 = new Date(0 + d1.getTimezoneOffset() * 60 * 1000 + 60 * 60 - * 1000 + 60 * 1000 + 1000); - - assertTrue("Created incorrect date", d1.equals(d2)); - } - - /** - * java.util.Date#Date(long) - */ - public void test_ConstructorJ() { - // Test for method java.util.Date(long) - assertTrue("Used to test", true); - } - - /** - * java.util.Date#Date(java.lang.String) - */ - public void test_ConstructorLjava_lang_String() { - // Test for method java.util.Date(java.lang.String) - Date d1 = new Date("January 1, 1970, 00:00:00 GMT"); // the epoch - Date d2 = new Date(0); // the epoch - assertTrue("Created incorrect date", d1.equals(d2)); - - try { - // Regression for HARMONY-238 - new Date(null); - fail("Constructor Date((String)null) should " - + "throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - } - - /** - * java.util.Date#after(java.util.Date) - */ - public void test_afterLjava_util_Date() { - // Test for method boolean java.util.Date.after(java.util.Date) - Date d1 = new Date(0); - Date d2 = new Date(1900000); - assertTrue("Older was returned as newer", d2.after(d1)); - assertTrue("Newer was returned as older", !d1.after(d2)); - - try { - d1.after(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.Date#before(java.util.Date) - */ - public void test_beforeLjava_util_Date() { - // Test for method boolean java.util.Date.before(java.util.Date) - Date d1 = new Date(0); - Date d2 = new Date(1900000); - assertTrue("Older was returned as newer", !d2.before(d1)); - assertTrue("Newer was returned as older", d1.before(d2)); - - try { - d1.before(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.Date#clone() - */ - public void test_clone() { - // Test for method java.lang.Object java.util.Date.clone() - Date d1 = new Date(100000); - Date d2 = (Date) d1.clone(); - assertTrue( - "Cloning date results in same reference--new date is equivalent", - d1 != d2); - assertTrue("Cloning date results unequal date", d1.equals(d2)); - } - - /** - * java.util.Date#compareTo(java.util.Date) - */ - public void test_compareToLjava_util_Date() { - // Test for method int java.util.Date.compareTo(java.util.Date) - final int someNumber = 10000; - Date d1 = new Date(someNumber); - Date d2 = new Date(someNumber); - Date d3 = new Date(someNumber + 1); - Date d4 = new Date(someNumber - 1); - assertEquals("Comparing a date to itself did not answer zero", 0, d1 - .compareTo(d1)); - assertEquals("Comparing equal dates did not answer zero", 0, d1 - .compareTo(d2)); - assertEquals("date1.compareTo(date2), where date1 > date2, did not result in 1", - 1, d1.compareTo(d4)); - assertEquals("date1.compareTo(date2), where date1 < date2, did not result in -1", - -1, d1.compareTo(d3)); - - try { - d1.compareTo(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.Date#equals(java.lang.Object) - */ - public void test_equalsLjava_lang_Object() { - // Test for method boolean java.util.Date.equals(java.lang.Object) - Date d1 = new Date(0); - Date d2 = new Date(1900000); - Date d3 = new Date(1900000); - assertTrue("Equality test failed", d2.equals(d3)); - assertTrue("Equality test failed", !d1.equals(d2)); - } - - /** - * java.util.Date#getDate() - */ - public void test_getDate() { - // Test for method int java.util.Date.getDate() - Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) - .getTime(); - assertEquals("Returned incorrect date", 13, d.getDate()); - } - - /** - * java.util.Date#getDay() - */ - public void test_getDay() { - // Test for method int java.util.Date.getDay() - Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) - .getTime(); - assertEquals("Returned incorrect day", 2, d.getDay()); - } - - /** - * java.util.Date#getHours() - */ - public void test_getHours() { - // Test for method int java.util.Date.getHours() - Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) - .getTime(); - assertEquals("Returned incorrect hours", 19, d.getHours()); - } - - /** - * java.util.Date#getMinutes() - */ - public void test_getMinutes() { - // Test for method int java.util.Date.getMinutes() - Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) - .getTime(); - assertEquals("Returned incorrect minutes", 9, d.getMinutes()); - } - - /** - * java.util.Date#getMonth() - */ - public void test_getMonth() { - // Test for method int java.util.Date.getMonth() - Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) - .getTime(); - assertEquals("Returned incorrect month", 9, d.getMonth()); - } - - /** - * java.util.Date#getSeconds() - */ - public void test_getSeconds() { - // Test for method int java.util.Date.getSeconds() - Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) - .getTime(); - assertEquals("Returned incorrect seconds", 0, d.getSeconds()); - } - - /** - * java.util.Date#getTime() - */ - public void test_getTime() { - // Test for method long java.util.Date.getTime() - Date d1 = new Date(0); - Date d2 = new Date(1900000); - assertEquals("Returned incorrect time", 1900000, d2.getTime()); - assertEquals("Returned incorrect time", 0, d1.getTime()); - } - - /** - * java.util.Date#getTimezoneOffset() - */ - public void test_getTimezoneOffset() { - // Test for method int java.util.Date.getTimezoneOffset() - assertTrue("Used to test", true); - int offset = new Date(96, 1, 14).getTimezoneOffset(); - assertTrue(offset > -720 && offset < 720); - } - - /** - * java.util.Date#getYear() - */ - public void test_getYear() { - // Test for method int java.util.Date.getYear() - Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) - .getTime(); - assertEquals("Returned incorrect year", 98, d.getYear()); - } - - /** - * java.util.Date#hashCode() - */ - public void test_hashCode() { - // Test for method int java.util.Date.hashCode() - Date d1 = new Date(0); - Date d2 = new Date(1900000); - assertEquals("Returned incorrect hash", 1900000, d2.hashCode()); - assertEquals("Returned incorrect hash", 0, d1.hashCode()); - } - - /** - * java.util.Date#parse(java.lang.String) - */ - public void test_parseLjava_lang_String() { - // Test for method long java.util.Date.parse(java.lang.String) - Date d = new Date(Date.parse("13 October 1998")); - GregorianCalendar cal = new GregorianCalendar(); - cal.setTime(d); - assertEquals("Parsed incorrect month", 9, cal.get(Calendar.MONTH)); - assertEquals("Parsed incorrect year", 1998, cal.get(Calendar.YEAR)); - assertEquals("Parsed incorrect date", 13, cal.get(Calendar.DATE)); - - d = new Date(Date.parse("Jan-12 1999")); - assertTrue("Wrong parsed date 1", d.equals(new GregorianCalendar(1999, - 0, 12).getTime())); - d = new Date(Date.parse("Jan12-1999")); - assertTrue("Wrong parsed date 2", d.equals(new GregorianCalendar(1999, - 0, 12).getTime())); - d = new Date(Date.parse("Jan12 69-1")); - cal.setTimeZone(TimeZone.getTimeZone("GMT")); - cal.clear(); - cal.set(1969, Calendar.JANUARY, 12, 1, 0); - assertTrue("Wrong parsed date 3", d.equals(cal.getTime())); - d = new Date(Date.parse("6:45:13 3/2/1200 MST")); - cal.setTimeZone(TimeZone.getTimeZone("MST")); - cal.clear(); - cal.set(1200, 2, 2, 6, 45, 13); - assertTrue("Wrong parsed date 4", d.equals(cal.getTime())); - d = new Date(Date.parse("Mon, 22 Nov 1999 12:52:06 GMT")); - cal.setTimeZone(TimeZone.getTimeZone("GMT")); - cal.clear(); - cal.set(1999, Calendar.NOVEMBER, 22, 12, 52, 06); - assertTrue("Wrong parsed date 5", d.equals(cal.getTime())); - - try { - // Regression for HARMONY-259 - Date.parse(null); - fail("Date.parse(null) should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - } - - /** - * java.util.Date#setDate(int) - */ - public void test_setDateI() { - // Test for method void java.util.Date.setDate(int) - Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) - .getTime(); - d.setDate(23); - assertEquals("Set incorrect date", 23, d.getDate()); - } - - /** - * java.util.Date#setHours(int) - */ - public void test_setHoursI() { - // Test for method void java.util.Date.setHours(int) - Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) - .getTime(); - d.setHours(23); - assertEquals("Set incorrect hours", 23, d.getHours()); - } - - /** - * java.util.Date#setMinutes(int) - */ - public void test_setMinutesI() { - // Test for method void java.util.Date.setMinutes(int) - Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) - .getTime(); - d.setMinutes(45); - assertEquals("Set incorrect mins", 45, d.getMinutes()); - } - - /** - * java.util.Date#setMonth(int) - */ - public void test_setMonthI() { - // Test for method void java.util.Date.setMonth(int) - Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) - .getTime(); - d.setMonth(0); - assertEquals("Set incorrect month", 0, d.getMonth()); - } - - /** - * java.util.Date#setSeconds(int) - */ - public void test_setSecondsI() { - // Test for method void java.util.Date.setSeconds(int) - Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) - .getTime(); - d.setSeconds(13); - assertEquals("Set incorrect seconds", 13, d.getSeconds()); - } - - /** - * java.util.Date#setTime(long) - */ - public void test_setTimeJ() { - // Test for method void java.util.Date.setTime(long) - Date d1 = new Date(0); - Date d2 = new Date(1900000); - d1.setTime(900); - d2.setTime(890000); - assertEquals("Returned incorrect time", 890000, d2.getTime()); - assertEquals("Returned incorrect time", 900, d1.getTime()); - } - - /** - * java.util.Date#setYear(int) - */ - public void test_setYearI() { - // Test for method void java.util.Date.setYear(int) - Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9) - .getTime(); - d.setYear(8); - assertEquals("Set incorrect year", 8, d.getYear()); - } - - /** - * java.util.Date#toGMTString() - */ - public void test_toGMTString() { - // Test for method java.lang.String java.util.Date.toGMTString() - assertEquals("Did not convert epoch to GMT string correctly", "1 Jan 1970 00:00:00 GMT", new Date(0) - .toGMTString()); - assertEquals("Did not convert epoch + 1yr to GMT string correctly", - "1 Jan 1971 00:00:00 GMT", new Date((long) 365 * 24 * 60 * 60 * 1000).toGMTString() - ); - } - - /** - * java.util.Date#toString() - */ - public void test_toString() { - // Test for method java.lang.String java.util.Date.toString() - Calendar cal = Calendar.getInstance(); - cal.set(Calendar.DATE, 1); - cal.set(Calendar.MONTH, Calendar.JANUARY); - cal.set(Calendar.YEAR, 1970); - cal.set(Calendar.HOUR_OF_DAY, 0); - cal.set(Calendar.MINUTE, 0); - cal.set(Calendar.SECOND, 0); - Date d = cal.getTime(); - String result = d.toString(); - assertTrue("Incorrect result: " + d, result - .startsWith("Thu Jan 01 00:00:00") - && result.endsWith("1970")); - - TimeZone tz = TimeZone.getDefault(); - TimeZone.setDefault(TimeZone.getTimeZone("GMT-5")); - try { - Date d1 = new Date(0); - assertTrue("Returned incorrect string: " + d1, d1.toString() - .equals("Wed Dec 31 19:00:00 GMT-05:00 1969")); - } finally { - TimeZone.setDefault(tz); - } - } - - /** - * java.util.Date#UTC(int, int, int, int, int, int) - */ - public void test_UTCIIIIII() { - // Test for method long java.util.Date.UTC(int, int, int, int, int, int) - assertTrue("Returned incorrect UTC value for epoch", Date.UTC(70, 0, 1, - 0, 0, 0) == (long) 0); - assertTrue("Returned incorrect UTC value for epoch +1yr", Date.UTC(71, - 0, 1, 0, 0, 0) == (long) 365 * 24 * 60 * 60 * 1000); - } - /** - * java.util.Date#toLocaleString() Test for method java.lang.String - * java.util.Date.toGMTString() - */ - public void test_toLocaleString() { - Locale loc = Locale.getDefault(); - Locale.setDefault(Locale.US); - TimeZone tz = TimeZone.getDefault(); - TimeZone.setDefault(TimeZone.getTimeZone("GMT")); - try { - assertEquals("Did not convert epoch to GMT string correctly", "Jan 1, 1970 12:00:00 AM", - new Date(0).toLocaleString()); - assertEquals("Did not convert epoch + 1yr to GMT string correctly", - "Jan 1, 1971 12:00:00 AM", new Date((long)365 * 24 * 60 * 60 * 1000) - .toLocaleString()); - } finally { - Locale.setDefault(loc); - TimeZone.setDefault(tz); - } - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/util/EmptyStackExceptionTest.java b/luni/src/test/java/tests/api/java/util/EmptyStackExceptionTest.java deleted file mode 100644 index 31ee1e2..0000000 --- a/luni/src/test/java/tests/api/java/util/EmptyStackExceptionTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.EmptyStackException; -import java.util.Stack; - -public class EmptyStackExceptionTest extends junit.framework.TestCase { - - Object[] objArray = new Object[10]; - Stack s; - - /** - * java.util.EmptyStackException#EmptyStackException() - */ - public void test_Constructor() { - // Test for method java.util.EmptyStackException() - try { - for (int counter = 0; counter < objArray.length + 1; counter++) - s.pop(); - } catch (EmptyStackException e) { - return; - } - fail("Expected EmptyStackException not thrown"); - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - for (int counter = 0; counter < objArray.length; counter++) { - objArray[counter] = new Integer(counter); - } - - s = new Stack(); - for (int counter = 0; counter < objArray.length; counter++) { - s.push(objArray[counter]); - } - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - objArray = null; - s = null; - } -} diff --git a/luni/src/test/java/tests/api/java/util/EnumMapTest.java b/luni/src/test/java/tests/api/java/util/EnumMapTest.java deleted file mode 100644 index 05826d1..0000000 --- a/luni/src/test/java/tests/api/java/util/EnumMapTest.java +++ /dev/null @@ -1,1175 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import dalvik.annotation.AndroidOnly; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; - -import org.apache.harmony.testframework.serialization.SerializationTest; - -import junit.framework.TestCase; - -public class EnumMapTest extends TestCase { - enum Size { - Small, Middle, Big {}; - } - - enum Color { - Red, Green, Blue {}; - } - - enum Empty { - //Empty - } - - private static class MockEntry<K, V> implements Map.Entry<K, V> { - private K key; - - private V value; - - public MockEntry(K key, V value) { - this.key = key; - this.value = value; - } - - @Override - public int hashCode() { - return (key == null ? 0 : key.hashCode()) - ^ (value == null ? 0 : value.hashCode()); - } - - public K getKey() { - return key; - } - - public V getValue() { - return value; - } - - public V setValue(V object) { - V oldValue = value; - value = object; - return oldValue; - } - } - - /** - * java.util.EnumMap#EnumMap(Class) - */ - @SuppressWarnings({ "unchecked", "boxing" }) - public void test_ConstructorLjava_lang_Class() { - try { - new EnumMap((Class) null); - fail("Expected NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - - - try { - new EnumMap(Size.Big.getClass()); - fail("Expected NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - - try { - new EnumMap(Integer.class); - fail("Expected NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - - EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class); - assertNull("Return non-null for non mapped key", enumColorMap.put( - Color.Green, 2)); - assertEquals("Get returned incorrect value for given key", 2, - enumColorMap.get(Color.Green)); - - EnumMap enumEmptyMap = new EnumMap<Empty, Double>(Empty.class); - try { - enumEmptyMap.put(Color.Red, 2); - fail("Expected ClassCastException"); - } catch (ClassCastException e) { - // Expected - } - - EnumMap enumSizeMap = new EnumMap(Size.class); - assertNull("Return non-null for non mapped key", enumSizeMap.put( - Size.Big, 2)); - assertEquals("Get returned incorrect value for given key", 2, - enumSizeMap.get(Size.Big)); - try { - enumSizeMap.put(Color.Red, 2); - fail("Expected ClassCastException"); - } catch (ClassCastException e) { - // Expected - } - - enumSizeMap = new EnumMap(Size.Middle.getClass()); - assertNull("Return non-null for non mapped key", enumSizeMap.put( - Size.Small, 1)); - assertEquals("Get returned incorrect value for given key", 1, - enumSizeMap.get(Size.Small)); - try { - enumSizeMap.put(Color.Red, 2); - fail("Expected ClassCastException"); - } catch (ClassCastException e) { - // Expected - } - } - - /** - * java.util.EnumMap#EnumMap(EnumMap) - */ - @SuppressWarnings({ "unchecked", "boxing" }) - public void test_ConstructorLjava_util_EnumMap() { - EnumMap enumMap; - EnumMap enumColorMap = null; - try { - enumMap = new EnumMap(enumColorMap); - fail("Expected NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - - enumColorMap = new EnumMap<Color, Double>(Color.class); - Double double1 = new Double(1); - enumColorMap.put(Color.Green, 2); - enumColorMap.put(Color.Blue, double1); - - enumMap = new EnumMap(enumColorMap); - assertEquals("Constructor fails", 2, enumMap.get(Color.Green)); - assertSame("Constructor fails", double1, enumMap.get(Color.Blue)); - assertNull("Constructor fails", enumMap.get(Color.Red)); - enumMap.put(Color.Red, 1); - assertEquals("Wrong value", 1, enumMap.get(Color.Red)); - - try { - enumMap.put(Size.Middle, 2); - fail("Expected ClassCastException"); - } catch (ClassCastException e) { - // Expected - } - } - - /** - * java.util.EnumMap#EnumMap(Map) - */ - @SuppressWarnings({ "unchecked", "boxing" }) - public void test_ConstructorLjava_util_Map() { - EnumMap enumMap; - Map enumColorMap = null; - try { - enumMap = new EnumMap(enumColorMap); - fail("Expected NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - enumColorMap = new EnumMap<Color, Double>(Color.class); - enumMap = new EnumMap(enumColorMap); - enumColorMap.put(Color.Blue, 3); - enumMap = new EnumMap(enumColorMap); - - HashMap hashColorMap = null; - try { - enumMap = new EnumMap(hashColorMap); - fail("Expected NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - - hashColorMap = new HashMap(); - try { - enumMap = new EnumMap(hashColorMap); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // Expected - } - - hashColorMap.put(Color.Green, 2); - enumMap = new EnumMap(hashColorMap); - assertEquals("Constructor fails", 2, enumMap.get(Color.Green)); - assertNull("Constructor fails", enumMap.get(Color.Red)); - enumMap.put(Color.Red, 1); - assertEquals("Wrong value", 1, enumMap.get(Color.Red)); - hashColorMap.put(Size.Big, 3); - try { - enumMap = new EnumMap(hashColorMap); - fail("Expected ClassCastException"); - } catch (ClassCastException e) { - // Expected - } - - hashColorMap = new HashMap(); - hashColorMap.put(new Integer(1), 1); - try { - enumMap = new EnumMap(hashColorMap); - fail("Expected ClassCastException"); - } catch (ClassCastException e) { - // Expected - } - } - - /** - * java.util.EnumMap#clear() - */ - @SuppressWarnings({ "unchecked", "boxing" }) - public void test_clear() { - EnumMap enumSizeMap = new EnumMap(Size.class); - enumSizeMap.put(Size.Small, 1); - enumSizeMap.clear(); - assertNull("Failed to clear all elements", enumSizeMap.get(Size.Small)); - } - - /** - * java.util.EnumMap#containsKey(Object) - */ - @SuppressWarnings( { "unchecked", "boxing" }) - public void test_containsKeyLjava_lang_Object() { - EnumMap enumSizeMap = new EnumMap(Size.class); - assertFalse("Returned true for uncontained key", enumSizeMap - .containsKey(Size.Small)); - enumSizeMap.put(Size.Small, 1); - assertTrue("Returned false for contained key", enumSizeMap - .containsKey(Size.Small)); - - enumSizeMap.put(Size.Big, null); - assertTrue("Returned false for contained key", enumSizeMap - .containsKey(Size.Big)); - - assertFalse("Returned true for uncontained key", enumSizeMap - .containsKey(Color.Red)); - assertFalse("Returned true for uncontained key", enumSizeMap - .containsKey(new Integer("3"))); - assertFalse("Returned true for uncontained key", enumSizeMap - .containsKey(null)); - } - - /** - * java.util.EnumMap#clone() - */ - @SuppressWarnings( { "unchecked", "boxing" }) - public void test_clone() { - EnumMap enumSizeMap = new EnumMap(Size.class); - Integer integer = new Integer("3"); - enumSizeMap.put(Size.Small, integer); - EnumMap enumSizeMapClone = enumSizeMap.clone(); - assertNotSame("Should not be same", enumSizeMap, enumSizeMapClone); - assertEquals("Clone answered unequal EnumMap", enumSizeMap, - enumSizeMapClone); - - assertSame("Should be same", enumSizeMap.get(Size.Small), - enumSizeMapClone.get(Size.Small)); - assertSame("Clone is not shallow clone", integer, enumSizeMapClone - .get(Size.Small)); - enumSizeMap.remove(Size.Small); - assertSame("Clone is not shallow clone", integer, enumSizeMapClone - .get(Size.Small)); - } - - /** - * java.util.EnumMap#containsValue(Object) - */ - @SuppressWarnings( { "unchecked", "boxing" }) - public void test_containsValueLjava_lang_Object() { - EnumMap enumSizeMap = new EnumMap(Size.class); - Double double1 = new Double(3); - Double double2 = new Double(3); - - assertFalse("Returned true for uncontained value", enumSizeMap - .containsValue(double1)); - enumSizeMap.put(Size.Middle, 2); - enumSizeMap.put(Size.Small, double1); - assertTrue("Returned false for contained value", enumSizeMap - .containsValue(double1)); - assertTrue("Returned false for contained value", enumSizeMap - .containsValue(double2)); - assertTrue("Returned false for contained value", enumSizeMap - .containsValue(2)); - assertFalse("Returned true for uncontained value", enumSizeMap - .containsValue(1)); - - assertFalse("Returned true for uncontained value", enumSizeMap - .containsValue(null)); - enumSizeMap.put(Size.Big, null); - assertTrue("Returned false for contained value", enumSizeMap - .containsValue(null)); - } - - /** - * java.util.EnumMap#entrySet() - */ - @AndroidOnly("Map.Entry is indirectly modified on RI when Iterator.next() is invoked") - @SuppressWarnings({ "unchecked", "boxing" }) - public void test_entrySet() { - EnumMap enumSizeMap = new EnumMap(Size.class); - enumSizeMap.put(Size.Middle, 1); - enumSizeMap.put(Size.Big, null); - MockEntry mockEntry = new MockEntry(Size.Middle, 1); - Set set = enumSizeMap.entrySet(); - - Set set1 = enumSizeMap.entrySet(); - assertSame("Should be same", set1, set); - try { - set.add(mockEntry); - fail("Should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException e) { - // Expected - } - - assertTrue("Returned false for contained object", set - .contains(mockEntry)); - mockEntry = new MockEntry(Size.Middle, null); - assertFalse("Returned true for uncontained object", set - .contains(mockEntry)); - assertFalse("Returned true for uncontained object", set - .contains(Size.Small)); - mockEntry = new MockEntry(new Integer(1), 1); - assertFalse("Returned true for uncontained object", set - .contains(mockEntry)); - assertFalse("Returned true for uncontained object", set - .contains(new Integer(1))); - - mockEntry = new MockEntry(Size.Big, null); - assertTrue("Returned false for contained object", set - .contains(mockEntry)); - assertTrue("Returned false when the object can be removed", set - .remove(mockEntry)); - assertFalse("Returned true for uncontained object", set - .contains(mockEntry)); - assertFalse("Returned true when the object can not be removed", set - .remove(mockEntry)); - mockEntry = new MockEntry(new Integer(1), 1); - assertFalse("Returned true when the object can not be removed", set - .remove(mockEntry)); - assertFalse("Returned true when the object can not be removed", set - .remove(new Integer(1))); - - // The set is backed by the map so changes to one are reflected by the - // other. - enumSizeMap.put(Size.Big, 3); - mockEntry = new MockEntry(Size.Big, 3); - assertTrue("Returned false for contained object", set - .contains(mockEntry)); - enumSizeMap.remove(Size.Big); - assertFalse("Returned true for uncontained object", set - .contains(mockEntry)); - - assertEquals("Wrong size", 1, set.size()); - set.clear(); - assertEquals("Wrong size", 0, set.size()); - - enumSizeMap = new EnumMap(Size.class); - enumSizeMap.put(Size.Middle, 1); - enumSizeMap.put(Size.Big, null); - set = enumSizeMap.entrySet(); - Collection c = new ArrayList(); - c.add(new MockEntry(Size.Middle, 1)); - assertTrue("Return wrong value", set.containsAll(c)); - assertTrue("Remove does not success", set.removeAll(c)); - - enumSizeMap.put(Size.Middle, 1); - c.add(new MockEntry(Size.Big, 3)); - assertTrue("Remove does not success", set.removeAll(c)); - assertFalse("Should return false", set.removeAll(c)); - assertEquals("Wrong size", 1, set.size()); - - enumSizeMap = new EnumMap(Size.class); - enumSizeMap.put(Size.Middle, 1); - enumSizeMap.put(Size.Big, null); - set = enumSizeMap.entrySet(); - c = new ArrayList(); - c.add(new MockEntry(Size.Middle, 1)); - c.add(new MockEntry(Size.Big, 3)); - - assertTrue("Retain does not success", set.retainAll(c)); - assertEquals("Wrong size", 1, set.size()); - assertFalse("Should return false", set.retainAll(c)); - - enumSizeMap = new EnumMap(Size.class); - enumSizeMap.put(Size.Middle, 1); - enumSizeMap.put(Size.Big, null); - - set = enumSizeMap.entrySet(); - Object[] array = set.toArray(); - assertEquals("Wrong length", 2, array.length); - Map.Entry entry = (Map.Entry) array[0]; - assertEquals("Wrong key", Size.Middle, entry.getKey()); - assertEquals("Wrong value", 1, entry.getValue()); - - Object[] array1 = new Object[10]; - array1 = set.toArray(); - assertEquals("Wrong length", 2, array1.length); - entry = (Map.Entry) array[0]; - assertEquals("Wrong key", Size.Middle, entry.getKey()); - assertEquals("Wrong value", 1, entry.getValue()); - - array1 = new Object[10]; - array1 = set.toArray(array1); - assertEquals("Wrong length", 10, array1.length); - entry = (Map.Entry) array[1]; - assertEquals("Wrong key", Size.Big, entry.getKey()); - assertNull("Should be null", array1[2]); - - set = enumSizeMap.entrySet(); - Integer integer = new Integer("1"); - assertFalse("Returned true when the object can not be removed", set - .remove(integer)); - assertTrue("Returned false when the object can be removed", set - .remove(entry)); - - enumSizeMap = new EnumMap(Size.class); - enumSizeMap.put(Size.Middle, 1); - enumSizeMap.put(Size.Big, null); - set = enumSizeMap.entrySet(); - Iterator iter = set.iterator(); - entry = (Map.Entry) iter.next(); - assertTrue("Returned false for contained object", set.contains(entry)); - mockEntry = new MockEntry(Size.Middle, 2); - assertFalse("Returned true for uncontained object", set - .contains(mockEntry)); - mockEntry = new MockEntry(new Integer(2), 2); - assertFalse("Returned true for uncontained object", set - .contains(mockEntry)); - entry = (Map.Entry) iter.next(); - assertTrue("Returned false for contained object", set.contains(entry)); - - enumSizeMap.put(Size.Middle, 1); - enumSizeMap.remove(Size.Big); - mockEntry = new MockEntry(Size.Big, null); - assertEquals("Wrong size", 1, set.size()); - assertFalse("Returned true for uncontained object", set.contains(mockEntry)); - enumSizeMap.put(Size.Big, 2); - mockEntry = new MockEntry(Size.Big, 2); - assertTrue("Returned false for contained object", set - .contains(mockEntry)); - - iter.remove(); - try { - iter.remove(); - fail("Should throw IllegalStateException"); - } catch (IllegalStateException e) { - // Expected - } - try { - entry.setValue(2); - fail("Should throw IllegalStateException"); - } catch (IllegalStateException e) { - // Expected - } - try { - set.contains(entry); - fail("Should throw IllegalStateException"); - } catch (IllegalStateException e) { - // Expected - } - - enumSizeMap = new EnumMap(Size.class); - enumSizeMap.put(Size.Middle, 1); - enumSizeMap.put(Size.Big, null); - set = enumSizeMap.entrySet(); - iter = set.iterator(); - entry = (Map.Entry) iter.next(); - assertEquals("Wrong key", Size.Middle, entry.getKey()); - - assertTrue("Returned false for contained object", set.contains(entry)); - enumSizeMap.put(Size.Middle, 3); - assertTrue("Returned false for contained object", set.contains(entry)); - entry.setValue(2); - assertTrue("Returned false for contained object", set.contains(entry)); - assertFalse("Returned true for uncontained object", set - .remove(new Integer(1))); - - iter.next(); - assertEquals("Wrong key", Size.Middle, entry.getKey()); - set.clear(); - assertEquals("Wrong size", 0, set.size()); - - enumSizeMap = new EnumMap(Size.class); - enumSizeMap.put(Size.Middle, 1); - enumSizeMap.put(Size.Big, null); - set = enumSizeMap.entrySet(); - iter = set.iterator(); - mockEntry = new MockEntry(Size.Middle, 1); - - assertFalse("Wrong result", entry.equals(mockEntry)); - try { - iter.remove(); - fail("Should throw IllegalStateException"); - } catch (IllegalStateException e) { - // Expected - } - entry = (Map.Entry) iter.next(); - assertEquals("Wrong key", Size.Middle, entry.getKey()); - assertTrue("Should return true", entry.equals(mockEntry)); - assertEquals("Should be equal", mockEntry.hashCode(), entry.hashCode()); - mockEntry = new MockEntry(Size.Big, 1); - assertFalse("Wrong result", entry.equals(mockEntry)); - - entry = (Map.Entry) iter.next(); - assertFalse("Wrong result", entry.equals(mockEntry)); - assertEquals("Wrong key", Size.Big, entry.getKey()); - iter.remove(); - assertFalse("Wrong result", entry.equals(mockEntry)); - assertEquals("Wrong size", 1, set.size()); - try { - iter.remove(); - fail("Should throw IllegalStateException"); - } catch (IllegalStateException e) { - // Expected - } - try { - iter.next(); - fail("Should throw NoSuchElementException"); - } catch (NoSuchElementException e) { - // Expected - } - } - - /** - * java.util.EnumMap#equals(Object) - */ - @SuppressWarnings( { "unchecked", "boxing" }) - public void test_equalsLjava_lang_Object() { - EnumMap enumMap = new EnumMap(Size.class); - enumMap.put(Size.Small, 1); - - EnumMap enumSizeMap = new EnumMap(Size.class); - assertFalse("Returned true for unequal EnumMap", enumSizeMap - .equals(enumMap)); - enumSizeMap.put(Size.Small, 1); - assertTrue("Returned false for equal EnumMap", enumSizeMap - .equals(enumMap)); - enumSizeMap.put(Size.Big, null); - assertFalse("Returned true for unequal EnumMap", enumSizeMap - .equals(enumMap)); - - enumMap.put(Size.Middle, null); - assertFalse("Returned true for unequal EnumMap", enumSizeMap - .equals(enumMap)); - enumMap.remove(Size.Middle); - enumMap.put(Size.Big, 3); - assertFalse("Returned true for unequal EnumMap", enumSizeMap - .equals(enumMap)); - enumMap.put(Size.Big, null); - assertTrue("Returned false for equal EnumMap", enumSizeMap - .equals(enumMap)); - - HashMap hashMap = new HashMap(); - hashMap.put(Size.Small, 1); - assertFalse("Returned true for unequal EnumMap", hashMap - .equals(enumMap)); - hashMap.put(Size.Big, null); - assertTrue("Returned false for equal EnumMap", enumMap.equals(hashMap)); - - assertFalse("Should return false", enumSizeMap - .equals(new Integer(1))); - } - - /** - * java.util.EnumMap#keySet() - */ - @SuppressWarnings( { "unchecked", "boxing" }) - public void test_keySet() { - EnumMap enumSizeMap = new EnumMap(Size.class); - enumSizeMap.put(Size.Middle, 2); - enumSizeMap.put(Size.Big, null); - Set set = enumSizeMap.keySet(); - - Set set1 = enumSizeMap.keySet(); - assertSame("Should be same", set1, set); - try { - set.add(Size.Big); - fail("Should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException e) { - // Expected - } - - assertTrue("Returned false for contained object", set - .contains(Size.Middle)); - assertTrue("Returned false for contained object", set - .contains(Size.Big)); - assertFalse("Returned true for uncontained object", set - .contains(Size.Small)); - assertFalse("Returned true for uncontained object", set - .contains(new Integer(1))); - assertTrue("Returned false when the object can be removed", set - .remove(Size.Big)); - assertFalse("Returned true for uncontained object", set - .contains(Size.Big)); - assertFalse("Returned true when the object can not be removed", set - .remove(Size.Big)); - assertFalse("Returned true when the object can not be removed", set - .remove(new Integer(1))); - - // The set is backed by the map so changes to one are reflected by the - // other. - enumSizeMap.put(Size.Big, 3); - assertTrue("Returned false for contained object", set - .contains(Size.Big)); - enumSizeMap.remove(Size.Big); - assertFalse("Returned true for uncontained object", set - .contains(Size.Big)); - - assertEquals("Wrong size", 1, set.size()); - set.clear(); - assertEquals("Wrong size", 0, set.size()); - - enumSizeMap = new EnumMap(Size.class); - enumSizeMap.put(Size.Middle, 1); - enumSizeMap.put(Size.Big, null); - set = enumSizeMap.keySet(); - Collection c = new ArrayList(); - c.add(Size.Big); - assertTrue("Should return true", set.containsAll(c)); - c.add(Size.Small); - assertFalse("Should return false", set.containsAll(c)); - assertTrue("Should return true", set.removeAll(c)); - assertEquals("Wrong size", 1, set.size()); - assertFalse("Should return false", set.removeAll(c)); - assertEquals("Wrong size", 1, set.size()); - try { - set.addAll(c); - fail("Should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException e) { - // Expected - } - - enumSizeMap.put(Size.Big, null); - assertEquals("Wrong size", 2, set.size()); - assertTrue("Should return true", set.retainAll(c)); - assertEquals("Wrong size", 1, set.size()); - assertFalse("Should return false", set.retainAll(c)); - assertEquals(1, set.size()); - Object[] array = set.toArray(); - assertEquals("Wrong length", 1, array.length); - assertEquals("Wrong key", Size.Big, array[0]); - - enumSizeMap = new EnumMap(Size.class); - enumSizeMap.put(Size.Middle, 1); - enumSizeMap.put(Size.Big, null); - set = enumSizeMap.keySet(); - c = new ArrayList(); - c.add(Color.Blue); - assertFalse("Should return false", set.remove(c)); - assertEquals("Wrong size", 2, set.size()); - assertTrue("Should return true", set.retainAll(c)); - assertEquals("Wrong size", 0, set.size()); - - enumSizeMap = new EnumMap(Size.class); - enumSizeMap.put(Size.Middle, 1); - enumSizeMap.put(Size.Big, null); - set = enumSizeMap.keySet(); - - Iterator iter = set.iterator(); - Enum enumKey = (Enum) iter.next(); - assertTrue("Returned false for contained object", set.contains(enumKey)); - enumKey = (Enum) iter.next(); - assertTrue("Returned false for contained object", set.contains(enumKey)); - - enumSizeMap.remove(Size.Big); - assertFalse("Returned true for uncontained object", set - .contains(enumKey)); - iter.remove(); - try { - iter.remove(); - fail("Should throw IllegalStateException"); - } catch (IllegalStateException e) { - // Expected - } - assertFalse("Returned true for uncontained object", set - .contains(enumKey)); - - iter = set.iterator(); - enumKey = (Enum) iter.next(); - assertTrue("Returned false for contained object", set.contains(enumKey)); - enumSizeMap.put(Size.Middle, 3); - assertTrue("Returned false for contained object", set.contains(enumKey)); - - enumSizeMap = new EnumMap(Size.class); - enumSizeMap.put(Size.Middle, 1); - enumSizeMap.put(Size.Big, null); - set = enumSizeMap.keySet(); - iter = set.iterator(); - try { - iter.remove(); - fail("Should throw IllegalStateException"); - } catch (IllegalStateException e) { - // Expected - } - enumKey = (Enum) iter.next(); - assertEquals("Wrong key", Size.Middle, enumKey); - assertSame("Wrong key", Size.Middle, enumKey); - assertFalse("Returned true for unequal object", iter.equals(enumKey)); - iter.remove(); - assertFalse("Returned true for uncontained object", set - .contains(enumKey)); - try { - iter.remove(); - fail("Should throw IllegalStateException"); - } catch (IllegalStateException e) { - // Expected - } - - assertEquals("Wrong size", 1, set.size()); - enumKey = (Enum) iter.next(); - assertEquals("Wrong key", Size.Big, enumKey); - iter.remove(); - try { - iter.next(); - fail("Should throw NoSuchElementException"); - } catch (NoSuchElementException e) { - // Expected - } - } - - /** - * java.util.EnumMap#get(Object) - */ - @SuppressWarnings({ "unchecked", "boxing" }) - public void test_getLjava_lang_Object() { - EnumMap enumSizeMap = new EnumMap(Size.class); - assertNull("Get returned non-null for non mapped key", enumSizeMap - .get(Size.Big)); - enumSizeMap.put(Size.Big, 1); - assertEquals("Get returned incorrect value for given key", 1, - enumSizeMap.get(Size.Big)); - - assertNull("Get returned non-null for non mapped key", enumSizeMap - .get(Size.Small)); - assertNull("Get returned non-null for non existent key", enumSizeMap - .get(Color.Red)); - assertNull("Get returned non-null for non existent key", enumSizeMap - .get(new Integer(1))); - assertNull("Get returned non-null for non existent key", enumSizeMap - .get(null)); - - EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class); - assertNull("Get returned non-null for non mapped key", enumColorMap - .get(Color.Green)); - enumColorMap.put(Color.Green, 2); - assertEquals("Get returned incorrect value for given key", 2, - enumColorMap.get(Color.Green)); - assertNull("Get returned non-null for non mapped key", enumColorMap - .get(Color.Blue)); - - enumColorMap.put(Color.Green, new Double(4)); - assertEquals("Get returned incorrect value for given key", - new Double(4), enumColorMap.get(Color.Green)); - enumColorMap.put(Color.Green, new Integer("3")); - assertEquals("Get returned incorrect value for given key", new Integer( - "3"), enumColorMap.get(Color.Green)); - enumColorMap.put(Color.Green, null); - assertNull("Can not handle null value", enumColorMap.get(Color.Green)); - Float f = new Float("3.4"); - enumColorMap.put(Color.Green, f); - assertSame("Get returned incorrect value for given key", f, - enumColorMap.get(Color.Green)); - } - - /** - * java.util.EnumMap#put(Object,Object) - */ - public void test_putLjava_lang_ObjectLjava_lang_Object() { - EnumMap enumSizeMap = new EnumMap(Size.class); - try { - enumSizeMap.put(Color.Red, 2); - fail("Expected ClassCastException"); - } catch (ClassCastException e) { - // Expected - } - assertNull("Return non-null for non mapped key", enumSizeMap.put( - Size.Small, 1)); - - EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class); - try { - enumColorMap.put(Size.Big, 2); - fail("Expected ClassCastException"); - } catch (ClassCastException e) { - // Expected - } - try { - enumColorMap.put(null, 2); - fail("Expected NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - assertNull("Return non-null for non mapped key", enumColorMap.put( - Color.Green, 2)); - assertEquals("Return wrong value", 2, enumColorMap.put(Color.Green, - new Double(4))); - assertEquals("Return wrong value", new Double(4), enumColorMap.put( - Color.Green, new Integer("3"))); - assertEquals("Return wrong value", new Integer("3"), enumColorMap.put( - Color.Green, null)); - Float f = new Float("3.4"); - assertNull("Return non-null for non mapped key", enumColorMap.put( - Color.Green, f)); - assertNull("Return non-null for non mapped key", enumColorMap.put( - Color.Blue, 2)); - assertEquals("Return wrong value", 2, enumColorMap.put(Color.Blue, - new Double(4))); - } - - /** - * java.util.EnumMap#putAll(Map) - */ - @SuppressWarnings({ "unchecked", "boxing" }) - public void test_putAllLjava_util_Map() { - EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class); - enumColorMap.put(Color.Green, 2); - - EnumMap enumSizeMap = new EnumMap(Size.class); - enumColorMap.putAll(enumSizeMap); - - enumSizeMap.put(Size.Big, 1); - try { - enumColorMap.putAll(enumSizeMap); - fail("Expected ClassCastException"); - } catch (ClassCastException e) { - // Expected - } - - EnumMap enumColorMap1 = new EnumMap<Color, Double>(Color.class); - enumColorMap1.put(Color.Blue, 3); - enumColorMap.putAll(enumColorMap1); - assertEquals("Get returned incorrect value for given key", 3, - enumColorMap.get(Color.Blue)); - assertEquals("Wrong Size", 2, enumColorMap.size()); - - enumColorMap = new EnumMap<Color, Double>(Color.class); - - HashMap hashColorMap = null; - try { - enumColorMap.putAll(hashColorMap); - fail("Expected NullPointerException"); - } catch (NullPointerException e) { - // Expected - } - - hashColorMap = new HashMap(); - enumColorMap.putAll(hashColorMap); - - hashColorMap.put(Color.Green, 2); - enumColorMap.putAll(hashColorMap); - assertEquals("Get returned incorrect value for given key", 2, - enumColorMap.get(Color.Green)); - assertNull("Get returned non-null for non mapped key", enumColorMap - .get(Color.Red)); - hashColorMap.put(Color.Red, new Integer(1)); - enumColorMap.putAll(hashColorMap); - assertEquals("Get returned incorrect value for given key", new Integer( - 2), enumColorMap.get(Color.Green)); - hashColorMap.put(Size.Big, 3); - try { - enumColorMap.putAll(hashColorMap); - fail("Expected ClassCastException"); - } catch (ClassCastException e) { - // Expected - } - - hashColorMap = new HashMap(); - hashColorMap.put(new Integer(1), 1); - try { - enumColorMap.putAll(hashColorMap); - fail("Expected ClassCastException"); - } catch (ClassCastException e) { - // Expected - } - } - - /** - * java.util.EnumMap#remove(Object) - */ - @SuppressWarnings({ "unchecked", "boxing" }) - public void test_removeLjava_lang_Object() { - EnumMap enumSizeMap = new EnumMap(Size.class); - assertNull("Remove of non-mapped key returned non-null", enumSizeMap - .remove(Size.Big)); - enumSizeMap.put(Size.Big, 3); - enumSizeMap.put(Size.Middle, 2); - - assertNull("Get returned non-null for non mapped key", enumSizeMap - .get(Size.Small)); - assertEquals("Remove returned incorrect value", 3, enumSizeMap - .remove(Size.Big)); - assertNull("Get returned non-null for non mapped key", enumSizeMap - .get(Size.Big)); - assertNull("Remove of non-mapped key returned non-null", enumSizeMap - .remove(Size.Big)); - assertNull("Remove of non-existent key returned non-null", enumSizeMap - .remove(Color.Red)); - assertNull("Remove of non-existent key returned non-null", enumSizeMap - .remove(new Double(4))); - assertNull("Remove of non-existent key returned non-null", enumSizeMap - .remove(null)); - - EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class); - assertNull("Get returned non-null for non mapped key", enumColorMap - .get(Color.Green)); - enumColorMap.put(Color.Green, new Double(4)); - assertEquals("Remove returned incorrect value", new Double(4), - enumColorMap.remove(Color.Green)); - assertNull("Get returned non-null for non mapped key", enumColorMap - .get(Color.Green)); - enumColorMap.put(Color.Green, null); - assertNull("Can not handle null value", enumColorMap - .remove(Color.Green)); - assertNull("Get returned non-null for non mapped key", enumColorMap - .get(Color.Green)); - } - - /** - * java.util.EnumMap#size() - */ - @SuppressWarnings({ "unchecked", "boxing" }) - public void test_size() { - EnumMap enumSizeMap = new EnumMap(Size.class); - assertEquals("Wrong size", 0, enumSizeMap.size()); - enumSizeMap.put(Size.Small, 1); - assertEquals("Wrong size", 1, enumSizeMap.size()); - enumSizeMap.put(Size.Small, 0); - assertEquals("Wrong size", 1, enumSizeMap.size()); - try { - enumSizeMap.put(Color.Red, 2); - fail("Expected ClassCastException"); - } catch (ClassCastException e) { - // Expected - } - assertEquals("Wrong size", 1, enumSizeMap.size()); - - enumSizeMap.put(Size.Middle, null); - assertEquals("Wrong size", 2, enumSizeMap.size()); - enumSizeMap.remove(Size.Big); - assertEquals("Wrong size", 2, enumSizeMap.size()); - enumSizeMap.remove(Size.Middle); - assertEquals("Wrong size", 1, enumSizeMap.size()); - enumSizeMap.remove(Color.Green); - assertEquals("Wrong size", 1, enumSizeMap.size()); - - EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class); - enumColorMap.put(Color.Green, 2); - assertEquals("Wrong size", 1, enumColorMap.size()); - enumColorMap.remove(Color.Green); - assertEquals("Wrong size", 0, enumColorMap.size()); - - EnumMap enumEmptyMap = new EnumMap<Empty, Double>(Empty.class); - assertEquals("Wrong size", 0, enumEmptyMap.size()); - } - - /** - * java.util.EnumMap#values() - */ - @SuppressWarnings( { "unchecked", "boxing" }) - public void test_values() { - EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class); - enumColorMap.put(Color.Red, 1); - enumColorMap.put(Color.Blue, null); - Collection collection = enumColorMap.values(); - - Collection collection1 = enumColorMap.values(); - assertSame("Should be same", collection1, collection); - try { - collection.add(new Integer(1)); - fail("Should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException e) { - // Expected - } - - assertTrue("Returned false for contained object", collection - .contains(1)); - assertTrue("Returned false for contained object", collection - .contains(null)); - assertFalse("Returned true for uncontained object", collection - .contains(2)); - - assertTrue("Returned false when the object can be removed", collection - .remove(null)); - assertFalse("Returned true for uncontained object", collection - .contains(null)); - assertFalse("Returned true when the object can not be removed", - collection.remove(null)); - - // The set is backed by the map so changes to one are reflected by the - // other. - enumColorMap.put(Color.Blue, 3); - assertTrue("Returned false for contained object", collection - .contains(3)); - enumColorMap.remove(Color.Blue); - assertFalse("Returned true for uncontained object", collection - .contains(3)); - - assertEquals("Wrong size", 1, collection.size()); - collection.clear(); - assertEquals("Wrong size", 0, collection.size()); - - enumColorMap = new EnumMap<Color, Double>(Color.class); - enumColorMap.put(Color.Red, 1); - enumColorMap.put(Color.Blue, null); - collection = enumColorMap.values(); - Collection c = new ArrayList(); - c.add(new Integer(1)); - assertTrue("Should return true", collection.containsAll(c)); - c.add(new Double(3.4)); - assertFalse("Should return false", collection.containsAll(c)); - assertTrue("Should return true", collection.removeAll(c)); - assertEquals("Wrong size", 1, collection.size()); - assertFalse("Should return false", collection.removeAll(c)); - assertEquals("Wrong size", 1, collection.size()); - try { - collection.addAll(c); - fail("Should throw UnsupportedOperationException"); - } catch (UnsupportedOperationException e) { - // Expected - } - - enumColorMap.put(Color.Red, 1); - assertEquals("Wrong size", 2, collection.size()); - assertTrue("Should return true", collection.retainAll(c)); - assertEquals("Wrong size", 1, collection.size()); - assertFalse("Should return false", collection.retainAll(c)); - assertEquals(1, collection.size()); - Object[] array = collection.toArray(); - assertEquals("Wrong length", 1, array.length); - assertEquals("Wrong key", 1, array[0]); - - enumColorMap = new EnumMap<Color, Double>(Color.class); - enumColorMap.put(Color.Red, 1); - enumColorMap.put(Color.Blue, null); - collection = enumColorMap.values(); - - assertEquals("Wrong size", 2, collection.size()); - assertFalse("Returned true when the object can not be removed", - collection.remove(new Integer("10"))); - - Iterator iter = enumColorMap.values().iterator(); - Object value = iter.next(); - assertTrue("Returned false for contained object", collection - .contains(value)); - value = iter.next(); - assertTrue("Returned false for contained object", collection - .contains(value)); - - enumColorMap.put(Color.Green, 1); - enumColorMap.remove(Color.Blue); - assertFalse("Returned true for uncontained object", collection - .contains(value)); - iter.remove(); - try { - iter.remove(); - fail("Should throw IllegalStateException"); - } catch (IllegalStateException e) { - // Expected - } - assertFalse("Returned true for uncontained object", collection - .contains(value)); - - iter = enumColorMap.values().iterator(); - value = iter.next(); - assertTrue("Returned false for contained object", collection - .contains(value)); - enumColorMap.put(Color.Green, 3); - assertTrue("Returned false for contained object", collection - .contains(value)); - assertTrue("Returned false for contained object", collection - .remove(new Integer("1"))); - assertEquals("Wrong size", 1, collection.size()); - collection.clear(); - assertEquals("Wrong size", 0, collection.size()); - - enumColorMap = new EnumMap<Color, Double>(Color.class); - Integer integer1 = new Integer(1); - enumColorMap.put(Color.Green, integer1); - enumColorMap.put(Color.Blue, null); - collection = enumColorMap.values(); - iter = enumColorMap.values().iterator(); - try { - iter.remove(); - fail("Should throw IllegalStateException"); - } catch (IllegalStateException e) { - // Expected - } - value = iter.next(); - assertEquals("Wrong value", integer1, value); - assertSame("Wrong value", integer1, value); - assertFalse("Returned true for unequal object", iter.equals(value)); - iter.remove(); - assertFalse("Returned true for unequal object", iter.equals(value)); - try { - iter.remove(); - fail("Should throw IllegalStateException"); - } catch (IllegalStateException e) { - // Expected - } - assertEquals("Wrong size", 1, collection.size()); - value = iter.next(); - assertFalse("Returned true for unequal object", iter.equals(value)); - iter.remove(); - try { - iter.next(); - fail("Should throw NoSuchElementException"); - } catch (NoSuchElementException e) { - // Expected - } - } - - /** - * serialization/deserialization. - */ - @SuppressWarnings({ "unchecked", "boxing" }) - public void testSerializationSelf() throws Exception { - EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class); - enumColorMap.put(Color.Blue, 3); - SerializationTest.verifySelf(enumColorMap); - } - - /** - * serialization/deserialization compatibility with RI. - */ - @SuppressWarnings({ "unchecked", "boxing" }) - public void testSerializationCompatibility() throws Exception { - EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class); - enumColorMap.put(Color.Red, 1); - enumColorMap.put(Color.Blue, 3); - SerializationTest.verifyGolden(this, enumColorMap); - } - - /** - * Sets up the fixture. - */ - @Override - protected void setUp() throws Exception { - super.setUp(); - } - - /** - * Tears down the fixture. - */ - @Override - protected void tearDown() throws Exception{ - super.tearDown(); - } -} diff --git a/luni/src/test/java/tests/api/java/util/EnumSetTest.java b/luni/src/test/java/tests/api/java/util/EnumSetTest.java deleted file mode 100644 index 2b33877..0000000 --- a/luni/src/test/java/tests/api/java/util/EnumSetTest.java +++ /dev/null @@ -1,2003 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.Set; - -import junit.framework.TestCase; - -import org.apache.harmony.testframework.serialization.SerializationTest; - -public class EnumSetTest extends TestCase { - static final boolean disableRIBugs = true; - - static enum EnumWithInnerClass { - a, b, c, d, e, f { - }, - } - - enum EnumWithAllInnerClass { - a {}, - b {}, - } - - static enum EnumFoo { - a, b,c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, aa, bb, cc, dd, ee, ff, gg, hh, ii, jj, kk, ll, - } - - static enum EmptyEnum { - // expected - } - - static enum HugeEnumWithInnerClass { - a{}, b{}, c{}, d{}, e{}, f{}, g{}, h{}, i{}, j{}, k{}, l{}, m{}, n{}, o{}, p{}, q{}, r{}, s{}, t{}, u{}, v{}, w{}, x{}, y{}, z{}, A{}, B{}, C{}, D{}, E{}, F{}, G{}, H{}, I{}, J{}, K{}, L{}, M{}, N{}, O{}, P{}, Q{}, R{}, S{}, T{}, U{}, V{}, W{}, X{}, Y{}, Z{}, aa{}, bb{}, cc{}, dd{}, ee{}, ff{}, gg{}, hh{}, ii{}, jj{}, kk{}, ll{}, mm{}, - } - - static enum HugeEnum { - a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, aa, bb, cc, dd, ee, ff, gg, hh, ii, jj, kk, ll, mm, - } - - static enum HugeEnumCount { - NO1, NO2, NO3, NO4, NO5, NO6, NO7, NO8, NO9, NO10, NO11, NO12, NO13, NO14, NO15, NO16, NO17, NO18, NO19, NO20, - NO21, NO22, NO23, NO24, NO25, NO26, NO27, NO28, NO29, NO30, NO31, NO32, NO33, NO34, NO35, NO36, NO37, NO38, NO39, NO40, - NO41, NO42, NO43, NO44, NO45, NO46, NO47, NO48, NO49, NO50, NO51, NO52, NO53, NO54, NO55, NO56, NO57, NO58, NO59, NO60, - NO61, NO62, NO63, NO64, NO65, NO66, NO67, NO68, NO69, NO70, NO71, NO72, NO73, NO74, NO75, NO76, NO77, NO78, NO79, NO80, - NO81, NO82, NO83, NO84, NO85, NO86, NO87, NO88, NO89, NO90, NO91, NO92, NO93, NO94, NO95, NO96, NO97, NO98, NO99, NO100, - NO101, NO102, NO103, NO104, NO105, NO106, NO107, NO108, NO109, NO110, NO111, NO112, NO113, NO114, NO115, NO116, NO117, NO118, NO119, NO120, - NO121, NO122, NO123, NO124, NO125, NO126, NO127, NO128, NO129, NO130, - } - - /** - * java.util.EnumSet#noneOf(java.lang.Class) - */ - @SuppressWarnings("unchecked") - public void test_NoneOf_LClass() { - try { - EnumSet.noneOf((Class) null); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - - try { - EnumSet.noneOf(Enum.class); - fail("Should throw ClassCastException"); - } catch (ClassCastException cce) { - // expected - } - - Class<EnumWithAllInnerClass> c = (Class<EnumWithAllInnerClass>) EnumWithAllInnerClass.a - .getClass(); - try { - EnumSet.noneOf(c); - fail("Should throw ClassCastException"); - } catch (ClassCastException e) { - // expected - } - - EnumSet<EnumWithAllInnerClass> setWithInnerClass = EnumSet - .noneOf(EnumWithAllInnerClass.class); - assertNotNull(setWithInnerClass); - - // test enum type with more than 64 elements - Class<HugeEnumWithInnerClass> hc = (Class<HugeEnumWithInnerClass>) HugeEnumWithInnerClass.a - .getClass(); - try { - EnumSet.noneOf(hc); - fail("Should throw ClassCastException"); - } catch (ClassCastException e) { - // expected - } - - EnumSet<HugeEnumWithInnerClass> hugeSetWithInnerClass = EnumSet - .noneOf(HugeEnumWithInnerClass.class); - assertNotNull(hugeSetWithInnerClass); - } - - /** - * java.util.HugeEnumSet#iterator() - */ - public void test_iterator_HugeEnumSet() { - EnumSet<HugeEnumCount> set; - Object[] array; - - // Test HugeEnumSet with 65 elements - // which is more than the bits of Long - set = EnumSet.range(HugeEnumCount.NO1, HugeEnumCount.NO65); - array = set.toArray(); - for (HugeEnumCount count : set) { - assertEquals(count, (HugeEnumCount) array[count.ordinal()]); - } - - // Test HugeEnumSet with 130 elements - // which is more than twice of the bits of Long - set = EnumSet.range(HugeEnumCount.NO1, HugeEnumCount.NO130); - array = set.toArray(); - for (HugeEnumCount count : set) { - assertEquals(count, (HugeEnumCount) array[count.ordinal()]); - } - } - - public void testRemoveIteratorRemoveFromHugeEnumSet() { - EnumSet<HugeEnumCount> set = EnumSet.noneOf(HugeEnumCount.class); - set.add(HugeEnumCount.NO64); - set.add(HugeEnumCount.NO65); - set.add(HugeEnumCount.NO128); - Iterator<HugeEnumCount> iterator = set.iterator(); - assertTrue(iterator.hasNext()); - assertEquals(HugeEnumCount.NO64, iterator.next()); - assertTrue(iterator.hasNext()); - iterator.remove(); - assertEquals(HugeEnumCount.NO65, iterator.next()); - assertTrue(iterator.hasNext()); - assertEquals(HugeEnumCount.NO128, iterator.next()); - assertFalse(iterator.hasNext()); - assertEquals(EnumSet.of(HugeEnumCount.NO65, HugeEnumCount.NO128), set); - iterator.remove(); - assertEquals(EnumSet.of(HugeEnumCount.NO65), set); - } - - /** - * java.util.EnumSet#allOf(java.lang.Class) - */ - @SuppressWarnings("unchecked") - public void test_AllOf_LClass() { - try { - EnumSet.allOf((Class) null); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - - try { - EnumSet.allOf(Enum.class); - fail("Should throw ClassCastException"); - } catch (ClassCastException cce) { - // expected - } - - EnumSet<EnumFoo> enumSet = EnumSet.allOf(EnumFoo.class); - assertEquals("Size of enumSet should be 64", 64, enumSet.size()); - - assertFalse( - "enumSet should not contain null value", enumSet.contains(null)); - assertTrue( - "enumSet should contain EnumFoo.a", enumSet.contains(EnumFoo.a)); - assertTrue( - "enumSet should contain EnumFoo.b", enumSet.contains(EnumFoo.b)); - - enumSet.add(EnumFoo.a); - assertEquals("Should be equal", 64, enumSet.size()); - - EnumSet<EnumFoo> anotherSet = EnumSet.allOf(EnumFoo.class); - assertEquals("Should be equal", enumSet, anotherSet); - assertNotSame("Should not be identical", enumSet, anotherSet); - - // test enum with more than 64 elements - EnumSet<HugeEnum> hugeEnumSet = EnumSet.allOf(HugeEnum.class); - assertEquals(65, hugeEnumSet.size()); - - assertFalse(hugeEnumSet.contains(null)); - assertTrue(hugeEnumSet.contains(HugeEnum.a)); - assertTrue(hugeEnumSet.contains(HugeEnum.b)); - - hugeEnumSet.add(HugeEnum.a); - assertEquals(65, hugeEnumSet.size()); - - EnumSet<HugeEnum> anotherHugeSet = EnumSet.allOf(HugeEnum.class); - assertEquals(hugeEnumSet, anotherHugeSet); - assertNotSame(hugeEnumSet, anotherHugeSet); - - } - - /** - * java.util.EnumSet#add(E) - */ - @SuppressWarnings("unchecked") - public void test_add_E() { - Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class); - set.add(EnumFoo.a); - set.add(EnumFoo.b); - - try { - set.add(null); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - - // test enum type with more than 64 elements - Set rawSet = set; - try { - rawSet.add(HugeEnumWithInnerClass.b); - fail("Should throw ClassCastException"); - } catch (ClassCastException e) { - // expected - } - - set.clear(); - try { - set.add(null); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - - boolean result = set.add(EnumFoo.a); - assertEquals("Size should be 1:", 1, set.size()); - assertTrue("Return value should be true", result); - - result = set.add(EnumFoo.a); - assertEquals("Size should be 1:", 1, set.size()); - assertFalse("Return value should be false", result); - - set.add(EnumFoo.b); - assertEquals("Size should be 2:", 2, set.size()); - - rawSet = set; - try { - rawSet.add(EnumWithAllInnerClass.a); - fail("Should throw ClassCastException"); - } catch(ClassCastException e) { - // expected - } - - try { - rawSet.add(EnumWithInnerClass.a); - fail("Should throw ClassCastException"); - } catch(ClassCastException e) { - // expected - } - - try { - rawSet.add(new Object()); - fail("Should throw ClassCastException"); - } catch(ClassCastException e) { - // expected - } - - // test enum type with more than 64 elements - Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class); - result = hugeSet.add(HugeEnum.a); - assertTrue(result); - - result = hugeSet.add(HugeEnum.a); - assertFalse(result); - - try { - hugeSet.add(null); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - - rawSet = hugeSet; - try { - rawSet.add(HugeEnumWithInnerClass.b); - fail("Should throw ClassCastException"); - } catch (ClassCastException e) { - // expected - } - - try { - rawSet.add(new Object()); - fail("Should throw ClassCastException"); - } catch (ClassCastException e) { - // expected - } - - result = hugeSet.add(HugeEnum.mm); - assertTrue(result); - result = hugeSet.add(HugeEnum.mm); - assertFalse(result); - assertEquals(2, hugeSet.size()); - - } - - /** - * java.util.EnumSet#addAll(Collection) - */ - @SuppressWarnings( { "unchecked", "boxing" }) - public void test_addAll_LCollection() { - - Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class); - assertEquals("Size should be 0:", 0, set.size()); - - try { - set.addAll(null); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - - Set emptySet = EnumSet.noneOf(EmptyEnum.class); - Enum[] elements = EmptyEnum.class.getEnumConstants(); - for(int i = 0; i < elements.length; i++) { - emptySet.add(elements[i]); - } - boolean result = set.addAll(emptySet); - assertFalse(result); - - Collection<EnumFoo> collection = new ArrayList<EnumFoo>(); - collection.add(EnumFoo.a); - collection.add(EnumFoo.b); - result = set.addAll(collection); - assertTrue("addAll should be successful", result); - assertEquals("Size should be 2:", 2, set.size()); - - set = EnumSet.noneOf(EnumFoo.class); - - Collection rawCollection = new ArrayList<Integer>(); - result = set.addAll(rawCollection); - assertFalse(result); - rawCollection.add(1); - try { - set.addAll(rawCollection); - fail("Should throw ClassCastException"); - } catch (ClassCastException e) { - // expected - } - - Set<EnumFoo> fullSet = EnumSet.noneOf(EnumFoo.class); - fullSet.add(EnumFoo.a); - fullSet.add(EnumFoo.b); - result = set.addAll(fullSet); - assertTrue("addAll should be successful", result); - assertEquals("Size of set should be 2", 2, set.size()); - - try { - fullSet.addAll(null); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - - Set fullSetWithSubclass = EnumSet.noneOf(EnumWithInnerClass.class); - elements = EnumWithInnerClass.class.getEnumConstants(); - for(int i = 0; i < elements.length; i++) { - fullSetWithSubclass.add(elements[i]); - } - try { - set.addAll(fullSetWithSubclass); - fail("Should throw ClassCastException"); - } catch (ClassCastException e) { - // expected - } - Set<EnumWithInnerClass> setWithSubclass = fullSetWithSubclass; - result = setWithSubclass.addAll(setWithSubclass); - assertFalse("Should return false", result); - - Set<EnumWithInnerClass> anotherSetWithSubclass = EnumSet - .noneOf(EnumWithInnerClass.class); - elements = EnumWithInnerClass.class.getEnumConstants(); - for(int i = 0; i < elements.length; i++) { - anotherSetWithSubclass.add((EnumWithInnerClass) elements[i]); - } - result = setWithSubclass.addAll(anotherSetWithSubclass); - assertFalse("Should return false", result); - - anotherSetWithSubclass.remove(EnumWithInnerClass.a); - result = setWithSubclass.addAll(anotherSetWithSubclass); - assertFalse("Should return false", result); - - // test enum type with more than 64 elements - Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class); - assertEquals(0, hugeSet.size()); - - try { - hugeSet.addAll(null); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - - hugeSet = EnumSet.allOf(HugeEnum.class); - result = hugeSet.addAll(hugeSet); - assertFalse(result); - - hugeSet = EnumSet.noneOf(HugeEnum.class); - Collection<HugeEnum> hugeCollection = new ArrayList<HugeEnum>(); - hugeCollection.add(HugeEnum.a); - hugeCollection.add(HugeEnum.b); - result = hugeSet.addAll(hugeCollection); - assertTrue(result); - assertEquals(2, set.size()); - - hugeSet = EnumSet.noneOf(HugeEnum.class); - - rawCollection = new ArrayList<Integer>(); - result = hugeSet.addAll(rawCollection); - assertFalse(result); - rawCollection.add(1); - try { - hugeSet.addAll(rawCollection); - fail("Should throw ClassCastException"); - } catch (ClassCastException e) { - // expected - } - - EnumSet<HugeEnum> aHugeSet = EnumSet.noneOf(HugeEnum.class); - aHugeSet.add(HugeEnum.a); - aHugeSet.add(HugeEnum.b); - result = hugeSet.addAll(aHugeSet); - assertTrue(result); - assertEquals(2, hugeSet.size()); - - try { - aHugeSet.addAll(null); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - - Set hugeSetWithSubclass = EnumSet.allOf(HugeEnumWithInnerClass.class); - try { - hugeSet.addAll(hugeSetWithSubclass); - fail("Should throw ClassCastException"); - } catch (ClassCastException e) { - // expected - } - Set<HugeEnumWithInnerClass> hugeSetWithInnerSubclass = hugeSetWithSubclass; - result = hugeSetWithInnerSubclass.addAll(hugeSetWithInnerSubclass); - assertFalse(result); - - Set<HugeEnumWithInnerClass> anotherHugeSetWithSubclass = EnumSet - .allOf(HugeEnumWithInnerClass.class); - result = hugeSetWithSubclass.addAll(anotherHugeSetWithSubclass); - assertFalse(result); - - anotherHugeSetWithSubclass.remove(HugeEnumWithInnerClass.a); - result = setWithSubclass.addAll(anotherSetWithSubclass); - assertFalse(result); - - } - - /** - * java.util.EnumSet#remove(Object) - */ - public void test_remove_LOject() { - Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class); - Enum[] elements = EnumFoo.class.getEnumConstants(); - for(int i = 0; i < elements.length; i++) { - set.add((EnumFoo) elements[i]); - } - - boolean result = set.remove(null); - assertFalse("'set' does not contain null", result); - - result = set.remove(EnumFoo.a); - assertTrue("Should return true", result); - result = set.remove(EnumFoo.a); - assertFalse("Should return false", result); - - assertEquals("Size of set should be 63:", 63, set.size()); - - result = set.remove(EnumWithInnerClass.a); - assertFalse("Should return false", result); - result = set.remove(EnumWithInnerClass.f); - assertFalse("Should return false", result); - - // test enum with more than 64 elements - Set<HugeEnum> hugeSet = EnumSet.allOf(HugeEnum.class); - - result = hugeSet.remove(null); - assertFalse("'set' does not contain null", result); - - result = hugeSet.remove(HugeEnum.a); - assertTrue("Should return true", result); - result = hugeSet.remove(HugeEnum.a); - assertFalse("Should return false", result); - - assertEquals("Size of set should be 64:", 64, hugeSet.size()); - - result = hugeSet.remove(HugeEnumWithInnerClass.a); - assertFalse("Should return false", result); - result = hugeSet.remove(HugeEnumWithInnerClass.f); - assertFalse("Should return false", result); - } - - /** - * java.util.EnumSet#equals(Object) - */ - public void test_equals_LObject() { - Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class); - Enum[] elements = EnumFoo.class.getEnumConstants(); - for(int i = 0; i < elements.length; i++) { - set.add((EnumFoo) elements[i]); - } - - assertFalse("Should return false", set.equals(null)); - assertFalse( - "Should return false", set.equals(new Object())); - - Set<EnumFoo> anotherSet = EnumSet.noneOf(EnumFoo.class); - elements = EnumFoo.class.getEnumConstants(); - for(int i = 0; i < elements.length; i++) { - anotherSet.add((EnumFoo) elements[i]); - } - assertTrue("Should return true", set.equals(anotherSet)); - - anotherSet.remove(EnumFoo.a); - assertFalse( - "Should return false", set.equals(anotherSet)); - - Set<EnumWithInnerClass> setWithInnerClass = EnumSet - .noneOf(EnumWithInnerClass.class); - elements = EnumWithInnerClass.class.getEnumConstants(); - for(int i = 0; i < elements.length; i++) { - setWithInnerClass.add((EnumWithInnerClass) elements[i]); - } - - assertFalse( - "Should return false", set.equals(setWithInnerClass)); - - setWithInnerClass.clear(); - set.clear(); - assertTrue("Should be equal", set.equals(setWithInnerClass)); - - // test enum type with more than 64 elements - Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class); - assertTrue(hugeSet.equals(set)); - - hugeSet = EnumSet.allOf(HugeEnum.class); - assertFalse(hugeSet.equals(null)); - assertFalse(hugeSet.equals(new Object())); - - Set<HugeEnum> anotherHugeSet = EnumSet.allOf(HugeEnum.class); - anotherHugeSet.remove(HugeEnum.a); - assertFalse(hugeSet.equals(anotherHugeSet)); - - Set<HugeEnumWithInnerClass> hugeSetWithInnerClass = EnumSet - .allOf(HugeEnumWithInnerClass.class); - assertFalse(hugeSet.equals(hugeSetWithInnerClass)); - hugeSetWithInnerClass.clear(); - hugeSet.clear(); - assertTrue(hugeSet.equals(hugeSetWithInnerClass)); - } - - /** - * java.util.EnumSet#clear() - */ - public void test_clear() { - Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class); - set.add(EnumFoo.a); - set.add(EnumFoo.b); - assertEquals("Size should be 2", 2, set.size()); - - set.clear(); - - assertEquals("Size should be 0", 0, set.size()); - - // test enum type with more than 64 elements - Set<HugeEnum> hugeSet = EnumSet.allOf(HugeEnum.class); - assertEquals(65, hugeSet.size()); - - boolean result = hugeSet.contains(HugeEnum.aa); - assertTrue(result); - - hugeSet.clear(); - assertEquals(0, hugeSet.size()); - result = hugeSet.contains(HugeEnum.aa); - assertFalse(result); - } - - /** - * java.util.EnumSet#size() - */ - public void test_size() { - Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class); - set.add(EnumFoo.a); - set.add(EnumFoo.b); - assertEquals("Size should be 2", 2, set.size()); - - // test enum type with more than 64 elements - Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class); - hugeSet.add(HugeEnum.a); - hugeSet.add(HugeEnum.bb); - assertEquals("Size should be 2", 2, hugeSet.size()); - } - - /** - * java.util.EnumSet#complementOf(java.util.EnumSet) - */ - public void test_ComplementOf_LEnumSet() { - - try { - EnumSet.complementOf((EnumSet<EnumFoo>) null); - fail("Should throw NullPointerException"); - } catch (NullPointerException npe) { - // expected - } - - EnumSet<EnumWithInnerClass> set = EnumSet - .noneOf(EnumWithInnerClass.class); - set.add(EnumWithInnerClass.d); - set.add(EnumWithInnerClass.e); - set.add(EnumWithInnerClass.f); - - assertEquals("Size should be 3:", 3, set.size()); - - EnumSet<EnumWithInnerClass> complementOfE = EnumSet.complementOf(set); - assertTrue(set.contains(EnumWithInnerClass.d)); - assertEquals( - "complementOfE should have size 3", 3, complementOfE.size()); - assertTrue("complementOfE should contain EnumWithSubclass.a:", - complementOfE.contains(EnumWithInnerClass.a)); - assertTrue("complementOfE should contain EnumWithSubclass.b:", - complementOfE.contains(EnumWithInnerClass.b)); - assertTrue("complementOfE should contain EnumWithSubclass.c:", - complementOfE.contains(EnumWithInnerClass.c)); - - // test enum type with more than 64 elements - EnumSet<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class); - assertEquals(0, hugeSet.size()); - Set<HugeEnum> complementHugeSet = EnumSet.complementOf(hugeSet); - assertEquals(65, complementHugeSet.size()); - - hugeSet.add(HugeEnum.A); - hugeSet.add(HugeEnum.mm); - complementHugeSet = EnumSet.complementOf(hugeSet); - assertEquals(63, complementHugeSet.size()); - - try { - EnumSet.complementOf((EnumSet<HugeEnum>) null); - fail("Should throw NullPointerException"); - } catch (NullPointerException npe) { - // expected - } - } - - /** - * java.util.EnumSet#contains(Object) - */ - public void test_contains_LObject() { - Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class); - Enum[] elements = EnumFoo.class.getEnumConstants(); - for(int i = 0; i < elements.length; i++) { - set.add((EnumFoo)elements[i]); - } - boolean result = set.contains(null); - assertFalse("Should not contain null:", result); - - result = set.contains(EnumFoo.a); - assertTrue("Should contain EnumFoo.a", result); - result = set.contains(EnumFoo.ll); - assertTrue("Should contain EnumFoo.ll", result); - - result = set.contains(EnumFoo.b); - assertTrue("Should contain EnumFoo.b", result); - - result = set.contains(new Object()); - assertFalse("Should not contain Object instance", result); - - result = set.contains(EnumWithInnerClass.a); - assertFalse("Should not contain EnumWithSubclass.a", result); - - set = EnumSet.noneOf(EnumFoo.class); - set.add(EnumFoo.aa); - set.add(EnumFoo.bb); - set.add(EnumFoo.cc); - - assertEquals("Size of set should be 3", 3, set.size()); - assertTrue("set should contain EnumFoo.aa", set.contains(EnumFoo.aa)); - - Set<EnumWithInnerClass> setWithSubclass = EnumSet - .noneOf(EnumWithInnerClass.class); - setWithSubclass.add(EnumWithInnerClass.a); - setWithSubclass.add(EnumWithInnerClass.b); - setWithSubclass.add(EnumWithInnerClass.c); - setWithSubclass.add(EnumWithInnerClass.d); - setWithSubclass.add(EnumWithInnerClass.e); - setWithSubclass.add(EnumWithInnerClass.f); - result = setWithSubclass.contains(EnumWithInnerClass.f); - assertTrue("Should contain EnumWithSubclass.f", result); - - // test enum type with more than 64 elements - Set<HugeEnum> hugeSet = EnumSet.allOf(HugeEnum.class); - hugeSet.add(HugeEnum.a); - result = hugeSet.contains(HugeEnum.a); - assertTrue(result); - - result = hugeSet.contains(HugeEnum.b); - assertTrue(result); - - result = hugeSet.contains(null); - assertFalse(result); - - result = hugeSet.contains(HugeEnum.a); - assertTrue(result); - - result = hugeSet.contains(HugeEnum.ll); - assertTrue(result); - - result = hugeSet.contains(new Object()); - assertFalse(result); - - result = hugeSet.contains(Enum.class); - assertFalse(result); - - } - - /** - * java.util.EnumSet#containsAll(Collection) - */ - @SuppressWarnings( { "unchecked", "boxing" }) - public void test_containsAll_LCollection() { - EnumSet<EnumFoo> set = EnumSet.noneOf(EnumFoo.class); - Enum[] elements = EnumFoo.class.getEnumConstants(); - for(int i = 0; i < elements.length; i++) { - set.add((EnumFoo)elements[i]); - } - try { - set.containsAll(null); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - - EnumSet<EmptyEnum> emptySet = EnumSet.noneOf(EmptyEnum.class); - elements = EmptyEnum.class.getEnumConstants(); - for(int i = 0; i < elements.length; i++) { - emptySet.add((EmptyEnum)elements[i]); - } - boolean result = set.containsAll(emptySet); - assertTrue("Should return true", result); - - Collection rawCollection = new ArrayList(); - result = set.containsAll(rawCollection); - assertTrue("Should contain empty collection:", result); - - rawCollection.add(1); - result = set.containsAll(rawCollection); - assertFalse("Should return false", result); - - rawCollection.add(EnumWithInnerClass.a); - result = set.containsAll(rawCollection); - assertFalse("Should return false", result); - - EnumSet rawSet = EnumSet.noneOf(EnumFoo.class); - result = set.containsAll(rawSet); - assertTrue("Should contain empty set", result); - - emptySet = EnumSet.noneOf(EmptyEnum.class); - result = set.containsAll(emptySet); - assertTrue("No class cast should be performed on empty set", result); - - Collection<EnumFoo> collection = new ArrayList<EnumFoo>(); - collection.add(EnumFoo.a); - result = set.containsAll(collection); - assertTrue("Should contain all elements in collection", result); - - EnumSet<EnumFoo> fooSet = EnumSet.noneOf(EnumFoo.class); - fooSet.add(EnumFoo.a); - result = set.containsAll(fooSet); - assertTrue("Should return true", result); - - set.clear(); - try { - set.containsAll(null); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - - Collection<EnumWithInnerClass> collectionWithSubclass = new ArrayList<EnumWithInnerClass>(); - collectionWithSubclass.add(EnumWithInnerClass.a); - result = set.containsAll(collectionWithSubclass); - assertFalse("Should return false", result); - - EnumSet<EnumWithInnerClass> setWithSubclass = EnumSet - .noneOf(EnumWithInnerClass.class); - setWithSubclass.add(EnumWithInnerClass.a); - result = set.containsAll(setWithSubclass); - assertFalse("Should return false", result); - - // test enum type with more than 64 elements - Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class); - hugeSet.add(HugeEnum.a); - hugeSet.add(HugeEnum.b); - hugeSet.add(HugeEnum.aa); - hugeSet.add(HugeEnum.bb); - hugeSet.add(HugeEnum.cc); - hugeSet.add(HugeEnum.dd); - - Set<HugeEnum> anotherHugeSet = EnumSet.noneOf(HugeEnum.class); - hugeSet.add(HugeEnum.b); - hugeSet.add(HugeEnum.cc); - result = hugeSet.containsAll(anotherHugeSet); - assertTrue(result); - - try { - hugeSet.containsAll(null); - fail("Should throw NullPointerException"); - } catch(NullPointerException e) { - // expected - } - - Set<HugeEnumWithInnerClass> hugeSetWithInnerClass = EnumSet - .noneOf(HugeEnumWithInnerClass.class); - hugeSetWithInnerClass.add(HugeEnumWithInnerClass.a); - hugeSetWithInnerClass.add(HugeEnumWithInnerClass.b); - result = hugeSetWithInnerClass.containsAll(hugeSetWithInnerClass); - assertTrue(result); - result = hugeSet.containsAll(hugeSetWithInnerClass); - assertFalse(result); - - rawCollection = new ArrayList(); - result = hugeSet.containsAll(rawCollection); - assertTrue("Should contain empty collection:", result); - - rawCollection.add(1); - result = hugeSet.containsAll(rawCollection); - assertFalse("Should return false", result); - - rawCollection.add(EnumWithInnerClass.a); - result = set.containsAll(rawCollection); - assertFalse("Should return false", result); - - rawSet = EnumSet.noneOf(HugeEnum.class); - result = hugeSet.containsAll(rawSet); - assertTrue("Should contain empty set", result); - - EnumSet<HugeEnumWithInnerClass> emptyHugeSet - = EnumSet.noneOf(HugeEnumWithInnerClass.class); - result = hugeSet.containsAll(emptyHugeSet); - assertTrue("No class cast should be performed on empty set", result); - - Collection<HugeEnum> hugeCollection = new ArrayList<HugeEnum>(); - hugeCollection.add(HugeEnum.a); - result = hugeSet.containsAll(hugeCollection); - assertTrue("Should contain all elements in collection", result); - - hugeSet.clear(); - try { - hugeSet.containsAll(null); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - - Collection<HugeEnumWithInnerClass> hugeCollectionWithSubclass = new ArrayList<HugeEnumWithInnerClass>(); - hugeCollectionWithSubclass.add(HugeEnumWithInnerClass.a); - result = hugeSet.containsAll(hugeCollectionWithSubclass); - assertFalse("Should return false", result); - - EnumSet<HugeEnumWithInnerClass> hugeSetWithSubclass = EnumSet - .noneOf(HugeEnumWithInnerClass.class); - hugeSetWithSubclass.add(HugeEnumWithInnerClass.a); - result = hugeSet.containsAll(hugeSetWithSubclass); - assertFalse("Should return false", result); - } - - /** - * java.util.EnumSet#copyOf(java.util.Collection) - */ - @SuppressWarnings("unchecked") - public void test_CopyOf_LCollection() { - try { - EnumSet.copyOf((Collection) null); - fail("Should throw NullPointerException"); - } catch (NullPointerException npe) { - // expected - } - - Collection collection = new ArrayList(); - try { - EnumSet.copyOf(collection); - fail("Should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - - collection.add(new Object()); - try { - EnumSet.copyOf(collection); - fail("Should throw ClassCastException"); - } catch (ClassCastException e) { - // expected - } - - Collection<EnumFoo> enumCollection = new ArrayList<EnumFoo>(); - enumCollection.add(EnumFoo.b); - - EnumSet<EnumFoo> copyOfEnumCollection = EnumSet.copyOf(enumCollection); - assertEquals("Size of copyOfEnumCollection should be 1:", - 1, copyOfEnumCollection.size()); - assertTrue("copyOfEnumCollection should contain EnumFoo.b:", - copyOfEnumCollection.contains(EnumFoo.b)); - - enumCollection.add(null); - assertEquals("Size of enumCollection should be 2:", - 2, enumCollection.size()); - - try { - copyOfEnumCollection = EnumSet.copyOf(enumCollection); - fail("Should throw NullPointerException"); - } catch (NullPointerException npe) { - // expected - } - - Collection rawEnumCollection = new ArrayList(); - rawEnumCollection.add(EnumFoo.a); - rawEnumCollection.add(EnumWithInnerClass.a); - try { - EnumSet.copyOf(rawEnumCollection); - fail("Should throw ClassCastException"); - } catch(ClassCastException e) { - // expected - } - - // test enum type with more than 64 elements - Collection<HugeEnum> hugeEnumCollection = new ArrayList<HugeEnum>(); - hugeEnumCollection.add(HugeEnum.b); - - EnumSet<HugeEnum> copyOfHugeEnumCollection = EnumSet.copyOf(hugeEnumCollection); - assertEquals(1, copyOfHugeEnumCollection.size()); - assertTrue(copyOfHugeEnumCollection.contains(HugeEnum.b)); - - hugeEnumCollection.add(null); - assertEquals(2, hugeEnumCollection.size()); - - try { - copyOfHugeEnumCollection = EnumSet.copyOf(hugeEnumCollection); - fail("Should throw NullPointerException"); - } catch (NullPointerException npe) { - // expected - } - - rawEnumCollection = new ArrayList(); - rawEnumCollection.add(HugeEnum.a); - rawEnumCollection.add(HugeEnumWithInnerClass.a); - try { - EnumSet.copyOf(rawEnumCollection); - fail("Should throw ClassCastException"); - } catch(ClassCastException e) { - // expected - } - } - - /** - * java.util.EnumSet#copyOf(java.util.EnumSet) - */ - @SuppressWarnings("unchecked") - public void test_CopyOf_LEnumSet() { - EnumSet<EnumWithInnerClass> enumSet = EnumSet - .noneOf(EnumWithInnerClass.class); - enumSet.add(EnumWithInnerClass.a); - enumSet.add(EnumWithInnerClass.f); - EnumSet<EnumWithInnerClass> copyOfE = EnumSet.copyOf(enumSet); - assertEquals("Size of enumSet and copyOfE should be equal", - enumSet.size(), copyOfE.size()); - - assertTrue("EnumWithSubclass.a should be contained in copyOfE", - copyOfE.contains(EnumWithInnerClass.a)); - assertTrue("EnumWithSubclass.f should be contained in copyOfE", - copyOfE.contains(EnumWithInnerClass.f)); - - Object[] enumValue = copyOfE.toArray(); - assertSame("enumValue[0] should be identical with EnumWithSubclass.a", - enumValue[0], EnumWithInnerClass.a); - assertSame("enumValue[1] should be identical with EnumWithSubclass.f", - enumValue[1], EnumWithInnerClass.f); - - try { - EnumSet.copyOf((EnumSet) null); - fail("Should throw NullPointerException"); - } catch (NullPointerException npe) { - // expected - } - - // test enum type with more than 64 elements - EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet - .noneOf(HugeEnumWithInnerClass.class); - hugeEnumSet.add(HugeEnumWithInnerClass.a); - hugeEnumSet.add(HugeEnumWithInnerClass.f); - EnumSet<HugeEnumWithInnerClass> copyOfHugeEnum = EnumSet.copyOf(hugeEnumSet); - assertEquals(enumSet.size(), copyOfE.size()); - - assertTrue(copyOfHugeEnum.contains(HugeEnumWithInnerClass.a)); - assertTrue(copyOfHugeEnum.contains(HugeEnumWithInnerClass.f)); - - Object[] hugeEnumValue = copyOfHugeEnum.toArray(); - assertSame(hugeEnumValue[0], HugeEnumWithInnerClass.a); - assertSame(hugeEnumValue[1], HugeEnumWithInnerClass.f); - } - - /** - * java.util.EnumSet#removeAll(Collection) - */ - @SuppressWarnings("unchecked") - public void test_removeAll_LCollection() { - Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class); - try { - set.removeAll(null); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - - set = EnumSet.allOf(EnumFoo.class); - assertEquals("Size of set should be 64:", 64, set.size()); - - try { - set.removeAll(null); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - - Collection<EnumFoo> collection = new ArrayList<EnumFoo>(); - collection.add(EnumFoo.a); - - boolean result = set.removeAll(collection); - assertTrue("Should return true", result); - assertEquals("Size of set should be 63", 63, set.size()); - - collection = new ArrayList(); - result = set.removeAll(collection); - assertFalse("Should return false", result); - - Set<EmptyEnum> emptySet = EnumSet.noneOf(EmptyEnum.class); - result = set.removeAll(emptySet); - assertFalse("Should return false", result); - - EnumSet<EnumFoo> emptyFooSet = EnumSet.noneOf(EnumFoo.class); - result = set.removeAll(emptyFooSet); - assertFalse("Should return false", result); - - emptyFooSet.add(EnumFoo.a); - result = set.removeAll(emptyFooSet); - assertFalse("Should return false", result); - - Set<EnumWithInnerClass> setWithSubclass = EnumSet - .noneOf(EnumWithInnerClass.class); - result = set.removeAll(setWithSubclass); - assertFalse("Should return false", result); - - setWithSubclass.add(EnumWithInnerClass.a); - result = set.removeAll(setWithSubclass); - assertFalse("Should return false", result); - - Set<EnumFoo> anotherSet = EnumSet.noneOf(EnumFoo.class); - anotherSet.add(EnumFoo.a); - - set = EnumSet.allOf(EnumFoo.class); - result = set.removeAll(anotherSet); - assertTrue("Should return true", result); - assertEquals("Size of set should be 63:", 63, set.size()); - - Set<EnumWithInnerClass> setWithInnerClass = EnumSet - .noneOf(EnumWithInnerClass.class); - setWithInnerClass.add(EnumWithInnerClass.a); - setWithInnerClass.add(EnumWithInnerClass.b); - - Set<EnumWithInnerClass> anotherSetWithInnerClass = EnumSet - .noneOf(EnumWithInnerClass.class); - anotherSetWithInnerClass.add(EnumWithInnerClass.c); - anotherSetWithInnerClass.add(EnumWithInnerClass.d); - result = anotherSetWithInnerClass.removeAll(setWithInnerClass); - assertFalse("Should return false", result); - - anotherSetWithInnerClass.add(EnumWithInnerClass.a); - result = anotherSetWithInnerClass.removeAll(setWithInnerClass); - assertTrue("Should return true", result); - assertEquals("Size of anotherSetWithInnerClass should remain 2", - 2, anotherSetWithInnerClass.size()); - - anotherSetWithInnerClass.remove(EnumWithInnerClass.c); - anotherSetWithInnerClass.remove(EnumWithInnerClass.d); - result = anotherSetWithInnerClass.remove(setWithInnerClass); - assertFalse("Should return false", result); - - Set rawSet = EnumSet.allOf(EnumWithAllInnerClass.class); - result = rawSet.removeAll(EnumSet.allOf(EnumFoo.class)); - assertFalse("Should return false", result); - - setWithInnerClass = EnumSet.allOf(EnumWithInnerClass.class); - anotherSetWithInnerClass = EnumSet.allOf(EnumWithInnerClass.class); - setWithInnerClass.remove(EnumWithInnerClass.a); - anotherSetWithInnerClass.remove(EnumWithInnerClass.f); - result = setWithInnerClass.removeAll(anotherSetWithInnerClass); - assertTrue("Should return true", result); - assertEquals("Size of setWithInnerClass should be 1", 1, setWithInnerClass.size()); - - result = setWithInnerClass.contains(EnumWithInnerClass.f); - assertTrue("Should return true", result); - - // test enum type with more than 64 elements - Set<HugeEnum> hugeSet = EnumSet.allOf(HugeEnum.class); - - Collection<HugeEnum> hugeCollection = new ArrayList<HugeEnum>(); - hugeCollection.add(HugeEnum.a); - - result = hugeSet.removeAll(hugeCollection); - assertTrue(result); - assertEquals(64, hugeSet.size()); - - collection = new ArrayList(); - result = hugeSet.removeAll(collection); - assertFalse(result); - - Set<HugeEnum> emptyHugeSet = EnumSet.noneOf(HugeEnum.class); - result = hugeSet.removeAll(emptyHugeSet); - assertFalse(result); - - Set<HugeEnumWithInnerClass> hugeSetWithSubclass = EnumSet - .noneOf(HugeEnumWithInnerClass.class); - result = hugeSet.removeAll(hugeSetWithSubclass); - assertFalse(result); - - hugeSetWithSubclass.add(HugeEnumWithInnerClass.a); - result = hugeSet.removeAll(hugeSetWithSubclass); - assertFalse(result); - - Set<HugeEnum> anotherHugeSet = EnumSet.noneOf(HugeEnum.class); - anotherHugeSet.add(HugeEnum.a); - - hugeSet = EnumSet.allOf(HugeEnum.class); - result = hugeSet.removeAll(anotherHugeSet); - assertTrue(result); - assertEquals(63, set.size()); - - Set<HugeEnumWithInnerClass> hugeSetWithInnerClass = EnumSet - .noneOf(HugeEnumWithInnerClass.class); - hugeSetWithInnerClass.add(HugeEnumWithInnerClass.a); - hugeSetWithInnerClass.add(HugeEnumWithInnerClass.b); - - Set<HugeEnumWithInnerClass> anotherHugeSetWithInnerClass = EnumSet - .noneOf(HugeEnumWithInnerClass.class); - anotherHugeSetWithInnerClass.add(HugeEnumWithInnerClass.c); - anotherHugeSetWithInnerClass.add(HugeEnumWithInnerClass.d); - result = anotherHugeSetWithInnerClass.removeAll(setWithInnerClass); - assertFalse("Should return false", result); - - anotherHugeSetWithInnerClass.add(HugeEnumWithInnerClass.a); - result = anotherHugeSetWithInnerClass.removeAll(hugeSetWithInnerClass); - assertTrue(result); - assertEquals(2, anotherHugeSetWithInnerClass.size()); - - anotherHugeSetWithInnerClass.remove(HugeEnumWithInnerClass.c); - anotherHugeSetWithInnerClass.remove(HugeEnumWithInnerClass.d); - result = anotherHugeSetWithInnerClass.remove(hugeSetWithInnerClass); - assertFalse(result); - - rawSet = EnumSet.allOf(HugeEnumWithInnerClass.class); - result = rawSet.removeAll(EnumSet.allOf(HugeEnum.class)); - assertFalse(result); - - hugeSetWithInnerClass = EnumSet.allOf(HugeEnumWithInnerClass.class); - anotherHugeSetWithInnerClass = EnumSet.allOf(HugeEnumWithInnerClass.class); - hugeSetWithInnerClass.remove(HugeEnumWithInnerClass.a); - anotherHugeSetWithInnerClass.remove(HugeEnumWithInnerClass.f); - result = hugeSetWithInnerClass.removeAll(anotherHugeSetWithInnerClass); - assertTrue(result); - assertEquals(1, hugeSetWithInnerClass.size()); - - result = hugeSetWithInnerClass.contains(HugeEnumWithInnerClass.f); - assertTrue(result); - } - - /** - * java.util.EnumSet#retainAll(Collection) - */ - @SuppressWarnings("unchecked") - public void test_retainAll_LCollection() { - Set<EnumFoo> set = EnumSet.allOf(EnumFoo.class); - - try { - set.retainAll(null); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - - set.clear(); - boolean result = set.retainAll(null); - assertFalse("Should return false", result); - - Collection rawCollection = new ArrayList(); - result = set.retainAll(rawCollection); - assertFalse("Should return false", result); - - rawCollection.add(EnumFoo.a); - result = set.retainAll(rawCollection); - assertFalse("Should return false", result); - - rawCollection.add(EnumWithInnerClass.a); - result = set.retainAll(rawCollection); - assertFalse("Should return false", result); - assertEquals("Size of set should be 0:", 0, set.size()); - - rawCollection.remove(EnumFoo.a); - result = set.retainAll(rawCollection); - assertFalse("Should return false", result); - - Set<EnumFoo> anotherSet = EnumSet.allOf(EnumFoo.class); - result = set.retainAll(anotherSet); - assertFalse("Should return false", result); - assertEquals("Size of set should be 0", 0, set.size()); - - Set<EnumWithInnerClass> setWithInnerClass = EnumSet - .allOf(EnumWithInnerClass.class); - result = set.retainAll(setWithInnerClass); - assertFalse("Should return false", result); - assertEquals("Size of set should be 0", 0, set.size()); - - setWithInnerClass = EnumSet.noneOf(EnumWithInnerClass.class); - result = set.retainAll(setWithInnerClass); - assertFalse("Should return false", result); - - Set<EmptyEnum> emptySet = EnumSet.allOf(EmptyEnum.class); - result = set.retainAll(emptySet); - assertFalse("Should return false", result); - - Set<EnumWithAllInnerClass> setWithAllInnerClass = EnumSet - .allOf(EnumWithAllInnerClass.class); - result = set.retainAll(setWithAllInnerClass); - assertFalse("Should return false", result); - - set.add(EnumFoo.a); - result = set.retainAll(setWithInnerClass); - assertTrue("Should return true", result); - assertEquals("Size of set should be 0", 0, set.size()); - - setWithInnerClass = EnumSet.allOf(EnumWithInnerClass.class); - setWithInnerClass.remove(EnumWithInnerClass.f); - Set<EnumWithInnerClass> anotherSetWithInnerClass = EnumSet - .noneOf(EnumWithInnerClass.class); - anotherSetWithInnerClass.add(EnumWithInnerClass.e); - anotherSetWithInnerClass.add(EnumWithInnerClass.f); - - result = setWithInnerClass.retainAll(anotherSetWithInnerClass); - assertTrue("Should return true", result); - result = setWithInnerClass.contains(EnumWithInnerClass.e); - assertTrue("Should contain EnumWithInnerClass.e", result); - result = setWithInnerClass.contains(EnumWithInnerClass.b); - assertFalse("Should not contain EnumWithInnerClass.b", result); - assertEquals("Size of set should be 1:", 1, setWithInnerClass.size()); - - anotherSetWithInnerClass = EnumSet.allOf(EnumWithInnerClass.class); - result = setWithInnerClass.retainAll(anotherSetWithInnerClass); - - assertFalse("Return value should be false", result); - - rawCollection = new ArrayList(); - rawCollection.add(EnumWithInnerClass.e); - rawCollection.add(EnumWithInnerClass.f); - result = setWithInnerClass.retainAll(rawCollection); - assertFalse("Should return false", result); - - set = EnumSet.allOf(EnumFoo.class); - set.remove(EnumFoo.a); - anotherSet = EnumSet.noneOf(EnumFoo.class); - anotherSet.add(EnumFoo.a); - result = set.retainAll(anotherSet); - assertTrue("Should return true", result); - assertEquals("size should be 0", 0, set.size()); - - // test enum type with more than 64 elements - Set<HugeEnum> hugeSet = EnumSet.allOf(HugeEnum.class); - - try { - hugeSet.retainAll(null); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - - hugeSet.clear(); - result = hugeSet.retainAll(null); - assertFalse(result); - - rawCollection = new ArrayList(); - result = hugeSet.retainAll(rawCollection); - assertFalse(result); - - rawCollection.add(HugeEnum.a); - result = hugeSet.retainAll(rawCollection); - assertFalse(result); - - rawCollection.add(HugeEnumWithInnerClass.a); - result = hugeSet.retainAll(rawCollection); - assertFalse(result); - assertEquals(0, set.size()); - - rawCollection.remove(HugeEnum.a); - result = set.retainAll(rawCollection); - assertFalse(result); - - Set<HugeEnum> anotherHugeSet = EnumSet.allOf(HugeEnum.class); - result = hugeSet.retainAll(anotherHugeSet); - assertFalse(result); - assertEquals(0, hugeSet.size()); - - Set<HugeEnumWithInnerClass> hugeSetWithInnerClass = EnumSet - .allOf(HugeEnumWithInnerClass.class); - result = hugeSet.retainAll(hugeSetWithInnerClass); - assertFalse(result); - assertEquals(0, hugeSet.size()); - - hugeSetWithInnerClass = EnumSet.noneOf(HugeEnumWithInnerClass.class); - result = hugeSet.retainAll(hugeSetWithInnerClass); - assertFalse(result); - - Set<HugeEnumWithInnerClass> hugeSetWithAllInnerClass = EnumSet - .allOf(HugeEnumWithInnerClass.class); - result = hugeSet.retainAll(hugeSetWithAllInnerClass); - assertFalse(result); - - hugeSet.add(HugeEnum.a); - result = hugeSet.retainAll(hugeSetWithInnerClass); - assertTrue(result); - assertEquals(0, hugeSet.size()); - - hugeSetWithInnerClass = EnumSet.allOf(HugeEnumWithInnerClass.class); - hugeSetWithInnerClass.remove(HugeEnumWithInnerClass.f); - Set<HugeEnumWithInnerClass> anotherHugeSetWithInnerClass = EnumSet - .noneOf(HugeEnumWithInnerClass.class); - anotherHugeSetWithInnerClass.add(HugeEnumWithInnerClass.e); - anotherHugeSetWithInnerClass.add(HugeEnumWithInnerClass.f); - - result = hugeSetWithInnerClass.retainAll(anotherHugeSetWithInnerClass); - assertTrue(result); - result = hugeSetWithInnerClass.contains(HugeEnumWithInnerClass.e); - assertTrue("Should contain HugeEnumWithInnerClass.e", result); - result = hugeSetWithInnerClass.contains(HugeEnumWithInnerClass.b); - assertFalse("Should not contain HugeEnumWithInnerClass.b", result); - assertEquals("Size of hugeSet should be 1:", 1, hugeSetWithInnerClass.size()); - - anotherHugeSetWithInnerClass = EnumSet.allOf(HugeEnumWithInnerClass.class); - result = hugeSetWithInnerClass.retainAll(anotherHugeSetWithInnerClass); - - assertFalse("Return value should be false", result); - - rawCollection = new ArrayList(); - rawCollection.add(HugeEnumWithInnerClass.e); - rawCollection.add(HugeEnumWithInnerClass.f); - result = hugeSetWithInnerClass.retainAll(rawCollection); - assertFalse(result); - - hugeSet = EnumSet.allOf(HugeEnum.class); - hugeSet.remove(HugeEnum.a); - anotherHugeSet = EnumSet.noneOf(HugeEnum.class); - anotherHugeSet.add(HugeEnum.a); - result = hugeSet.retainAll(anotherHugeSet); - assertTrue(result); - assertEquals(0, hugeSet.size()); - } - - /** - * java.util.EnumSet#iterator() - */ - public void test_iterator() { - Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class); - set.add(EnumFoo.a); - set.add(EnumFoo.b); - - Iterator<EnumFoo> iterator = set.iterator(); - Iterator<EnumFoo> anotherIterator = set.iterator(); - assertNotSame("Should not be same", iterator, anotherIterator); - try { - iterator.remove(); - fail("Should throw IllegalStateException"); - } catch (IllegalStateException e) { - // expectedd - } - - assertTrue("Should has next element:", iterator.hasNext()); - assertSame("Should be identical", EnumFoo.a, iterator.next()); - iterator.remove(); - assertTrue("Should has next element:", iterator.hasNext()); - assertSame("Should be identical", EnumFoo.b, iterator.next()); - assertFalse("Should not has next element:", iterator.hasNext()); - assertFalse("Should not has next element:", iterator.hasNext()); - - assertEquals("Size should be 1:", 1, set.size()); - - try { - iterator.next(); - fail("Should throw NoSuchElementException"); - } catch (NoSuchElementException e) { - // expected - } - set = EnumSet.noneOf(EnumFoo.class); - set.add(EnumFoo.a); - iterator = set.iterator(); - assertEquals("Should be equal", EnumFoo.a, iterator.next()); - iterator.remove(); - try { - iterator.remove(); - fail("Should throw IllegalStateException"); - } catch(IllegalStateException e) { - // expected - } - - Set<EmptyEnum> emptySet = EnumSet.allOf(EmptyEnum.class); - Iterator<EmptyEnum> emptyIterator = emptySet.iterator(); - try { - emptyIterator.next(); - fail("Should throw NoSuchElementException"); - } catch (NoSuchElementException e) { - // expected - } - - Set<EnumWithInnerClass> setWithSubclass = EnumSet - .allOf(EnumWithInnerClass.class); - setWithSubclass.remove(EnumWithInnerClass.e); - Iterator<EnumWithInnerClass> iteratorWithSubclass = setWithSubclass - .iterator(); - assertSame("Should be same", EnumWithInnerClass.a, iteratorWithSubclass.next()); - - assertTrue("Should return true", iteratorWithSubclass.hasNext()); - assertSame("Should be same", EnumWithInnerClass.b, iteratorWithSubclass.next()); - - setWithSubclass.remove(EnumWithInnerClass.c); - assertTrue("Should return true", iteratorWithSubclass.hasNext()); - assertSame("Should be same", EnumWithInnerClass.c, iteratorWithSubclass.next()); - - assertTrue("Should return true", iteratorWithSubclass.hasNext()); - assertSame("Should be same", EnumWithInnerClass.d, iteratorWithSubclass.next()); - - setWithSubclass.add(EnumWithInnerClass.e); - assertTrue("Should return true", iteratorWithSubclass.hasNext()); - assertSame("Should be same", EnumWithInnerClass.f, iteratorWithSubclass.next()); - - set = EnumSet.noneOf(EnumFoo.class); - iterator = set.iterator(); - try { - iterator.next(); - fail("Should throw NoSuchElementException"); - } catch (NoSuchElementException e) { - // expected - } - - set.add(EnumFoo.a); - iterator = set.iterator(); - assertEquals("Should return EnumFoo.a", EnumFoo.a, iterator.next()); - assertEquals("Size of set should be 1", 1, set.size()); - iterator.remove(); - assertEquals("Size of set should be 0", 0, set.size()); - assertFalse("Should return false", set.contains(EnumFoo.a)); - - set.add(EnumFoo.a); - set.add(EnumFoo.b); - iterator = set.iterator(); - assertEquals("Should be equals", EnumFoo.a, iterator.next()); - iterator.remove(); - try { - iterator.remove(); - fail("Should throw IllegalStateException"); - } catch(IllegalStateException e) { - // expected - } - - assertTrue("Should have next element", iterator.hasNext()); - try { - iterator.remove(); - fail("Should throw IllegalStateException"); - } catch (IllegalStateException e) { - // expected - } - assertEquals("Size of set should be 1", 1, set.size()); - assertTrue("Should have next element", iterator.hasNext()); - assertEquals("Should return EnumFoo.b", EnumFoo.b, iterator.next()); - set.remove(EnumFoo.b); - assertEquals("Size of set should be 0", 0, set.size()); - iterator.remove(); - assertFalse("Should return false", set.contains(EnumFoo.a)); - - // RI's bug, EnumFoo.b should not exist at the moment. - if (!disableRIBugs) { - assertFalse("Should return false", set.contains(EnumFoo.b)); - } - - // test enum type with more than 64 elements - Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class); - hugeSet.add(HugeEnum.a); - hugeSet.add(HugeEnum.b); - - Iterator<HugeEnum> hIterator = hugeSet.iterator(); - Iterator<HugeEnum> anotherHugeIterator = hugeSet.iterator(); - assertNotSame(hIterator, anotherHugeIterator); - try { - hIterator.remove(); - fail("Should throw IllegalStateException"); - } catch (IllegalStateException e) { - // expectedd - } - - assertTrue(hIterator.hasNext()); - assertSame(HugeEnum.a, hIterator.next()); - hIterator.remove(); - assertTrue(hIterator.hasNext()); - assertSame(HugeEnum.b, hIterator.next()); - assertFalse(hIterator.hasNext()); - assertFalse(hIterator.hasNext()); - - assertEquals(1, hugeSet.size()); - - try { - hIterator.next(); - fail("Should throw NoSuchElementException"); - } catch (NoSuchElementException e) { - // expected - } - - Set<HugeEnumWithInnerClass> hugeSetWithSubclass = EnumSet - .allOf(HugeEnumWithInnerClass.class); - hugeSetWithSubclass.remove(HugeEnumWithInnerClass.e); - Iterator<HugeEnumWithInnerClass> hugeIteratorWithSubclass = hugeSetWithSubclass - .iterator(); - assertSame(HugeEnumWithInnerClass.a, hugeIteratorWithSubclass.next()); - - assertTrue(hugeIteratorWithSubclass.hasNext()); - assertSame(HugeEnumWithInnerClass.b, hugeIteratorWithSubclass.next()); - - setWithSubclass.remove(HugeEnumWithInnerClass.c); - assertTrue(hugeIteratorWithSubclass.hasNext()); - assertSame(HugeEnumWithInnerClass.c, hugeIteratorWithSubclass.next()); - - assertTrue(hugeIteratorWithSubclass.hasNext()); - assertSame(HugeEnumWithInnerClass.d, hugeIteratorWithSubclass.next()); - - hugeSetWithSubclass.add(HugeEnumWithInnerClass.e); - assertTrue(hugeIteratorWithSubclass.hasNext()); - assertSame(HugeEnumWithInnerClass.f, hugeIteratorWithSubclass.next()); - - hugeSet = EnumSet.noneOf(HugeEnum.class); - hIterator = hugeSet.iterator(); - try { - hIterator.next(); - fail("Should throw NoSuchElementException"); - } catch (NoSuchElementException e) { - // expected - } - - hugeSet.add(HugeEnum.a); - hIterator = hugeSet.iterator(); - assertEquals(HugeEnum.a, hIterator.next()); - assertEquals(1, hugeSet.size()); - hIterator.remove(); - assertEquals(0, hugeSet.size()); - assertFalse(hugeSet.contains(HugeEnum.a)); - - hugeSet.add(HugeEnum.a); - hugeSet.add(HugeEnum.b); - hIterator = hugeSet.iterator(); - hIterator.next(); - hIterator.remove(); - - assertTrue(hIterator.hasNext()); - try { - hIterator.remove(); - fail("Should throw IllegalStateException"); - } catch (IllegalStateException e) { - // expected - } - assertEquals(1, hugeSet.size()); - assertTrue(hIterator.hasNext()); - assertEquals(HugeEnum.b, hIterator.next()); - hugeSet.remove(HugeEnum.b); - assertEquals(0, hugeSet.size()); - hIterator.remove(); - assertFalse(hugeSet.contains(HugeEnum.a)); - // RI's bug, EnumFoo.b should not exist at the moment. - if(!disableRIBugs) { - assertFalse("Should return false", set.contains(EnumFoo.b)); - } - } - - /** - * java.util.EnumSet#of(E) - */ - public void test_Of_E() { - EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a); - assertEquals("enumSet should have length 1:", 1, enumSet.size()); - - assertTrue("enumSet should contain EnumWithSubclass.a:", - enumSet.contains(EnumWithInnerClass.a)); - - try { - EnumSet.of((EnumWithInnerClass) null); - fail("Should throw NullPointerException"); - } catch (NullPointerException npe) { - // expected - } - - // test enum type with more than 64 elements - EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a); - assertEquals(1, hugeEnumSet.size()); - - assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a)); - } - - /** - * java.util.EnumSet#of(E, E) - */ - public void test_Of_EE() { - EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a, - EnumWithInnerClass.b); - assertEquals("enumSet should have length 2:", 2, enumSet.size()); - - assertTrue("enumSet should contain EnumWithSubclass.a:", - enumSet.contains(EnumWithInnerClass.a)); - assertTrue("enumSet should contain EnumWithSubclass.b:", - enumSet.contains(EnumWithInnerClass.b)); - - try { - EnumSet.of((EnumWithInnerClass) null, EnumWithInnerClass.a); - fail("Should throw NullPointerException"); - } catch (NullPointerException npe) { - // expected - } - - try { - EnumSet.of( EnumWithInnerClass.a, (EnumWithInnerClass) null); - fail("Should throw NullPointerException"); - } catch (NullPointerException npe) { - // expected - } - - try { - EnumSet.of( (EnumWithInnerClass) null, (EnumWithInnerClass) null); - fail("Should throw NullPointerException"); - } catch (NullPointerException npe) { - // expected - } - - enumSet = EnumSet.of(EnumWithInnerClass.a, EnumWithInnerClass.a); - assertEquals("Size of enumSet should be 1", - 1, enumSet.size()); - - // test enum type with more than 64 elements - EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a, - HugeEnumWithInnerClass.b); - assertEquals(2, hugeEnumSet.size()); - - assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a)); - assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.b)); - - try { - EnumSet.of((HugeEnumWithInnerClass) null, HugeEnumWithInnerClass.a); - fail("Should throw NullPointerException"); - } catch (NullPointerException npe) { - // expected - } - - try { - EnumSet.of( HugeEnumWithInnerClass.a, (HugeEnumWithInnerClass) null); - fail("Should throw NullPointerException"); - } catch (NullPointerException npe) { - // expected - } - - try { - EnumSet.of( (HugeEnumWithInnerClass) null, (HugeEnumWithInnerClass) null); - fail("Should throw NullPointerException"); - } catch (NullPointerException npe) { - // expected - } - - hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a, HugeEnumWithInnerClass.a); - assertEquals(1, hugeEnumSet.size()); - } - - /** - * java.util.EnumSet#of(E, E, E) - */ - public void test_Of_EEE() { - EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a, - EnumWithInnerClass.b, EnumWithInnerClass.c); - assertEquals("Size of enumSet should be 3:", 3, enumSet.size()); - - assertTrue( - "enumSet should contain EnumWithSubclass.a:", enumSet.contains(EnumWithInnerClass.a)); - assertTrue("Should return true", enumSet.contains(EnumWithInnerClass.c)); - - try { - EnumSet.of((EnumWithInnerClass) null, null, null); - fail("Should throw NullPointerException"); - } catch (NullPointerException npe) { - // expected - } - - enumSet = EnumSet.of(EnumWithInnerClass.a, EnumWithInnerClass.b, - EnumWithInnerClass.b); - assertEquals("enumSet should contain 2 elements:", 2, enumSet.size()); - - // test enum type with more than 64 elements - EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a, - HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.c); - assertEquals(3, hugeEnumSet.size()); - - assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a)); - assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.c)); - - try { - EnumSet.of((HugeEnumWithInnerClass) null, null, null); - fail("Should throw NullPointerException"); - } catch (NullPointerException npe) { - // expected - } - - hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a, HugeEnumWithInnerClass.b, - HugeEnumWithInnerClass.b); - assertEquals(2, hugeEnumSet.size()); - } - - /** - * java.util.EnumSet#of(E, E, E, E) - */ - public void test_Of_EEEE() { - EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a, - EnumWithInnerClass.b, EnumWithInnerClass.c, - EnumWithInnerClass.d); - assertEquals("Size of enumSet should be 4", 4, enumSet.size()); - - assertTrue( - "enumSet should contain EnumWithSubclass.a:", enumSet.contains(EnumWithInnerClass.a)); - assertTrue("enumSet should contain EnumWithSubclass.d:", enumSet - .contains(EnumWithInnerClass.d)); - - try { - EnumSet.of((EnumWithInnerClass) null, null, null, null); - fail("Should throw NullPointerException"); - } catch (NullPointerException npe) { - // expected - } - - // test enum type with more than 64 elements - EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a, - HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.c, - HugeEnumWithInnerClass.d); - assertEquals(4, hugeEnumSet.size()); - - assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a)); - assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.d)); - - try { - EnumSet.of((HugeEnumWithInnerClass) null, null, null, null); - fail("Should throw NullPointerException"); - } catch (NullPointerException npe) { - // expected - } - } - - /** - * java.util.EnumSet#of(E, E, E, E, E) - */ - public void test_Of_EEEEE() { - EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a, - EnumWithInnerClass.b, EnumWithInnerClass.c, - EnumWithInnerClass.d, EnumWithInnerClass.e); - assertEquals("Size of enumSet should be 5:", 5, enumSet.size()); - - assertTrue("Should return true", enumSet.contains(EnumWithInnerClass.a)); - assertTrue("Should return true", enumSet.contains(EnumWithInnerClass.e)); - - try { - EnumSet.of((EnumWithInnerClass) null, null, null, null, null); - fail("Should throw NullPointerException"); - } catch (NullPointerException npe) { - // expected - } - - // test enum with more than 64 elements - EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a, - HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.c, - HugeEnumWithInnerClass.d, HugeEnumWithInnerClass.e); - assertEquals(5, hugeEnumSet.size()); - - assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a)); - assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.e)); - - try { - EnumSet.of((HugeEnumWithInnerClass) null, null, null, null, null); - fail("Should throw NullPointerException"); - } catch (NullPointerException npe) { - // expected - } - } - - /** - * java.util.EnumSet#of(E, E...) - */ - public void test_Of_EEArray() { - EnumWithInnerClass[] enumArray = new EnumWithInnerClass[] { - EnumWithInnerClass.b, EnumWithInnerClass.c }; - EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a, - enumArray); - assertEquals("Should be equal", 3, enumSet.size()); - - assertTrue("Should return true", enumSet.contains(EnumWithInnerClass.a)); - assertTrue("Should return true", enumSet.contains(EnumWithInnerClass.c)); - - try { - EnumSet.of(EnumWithInnerClass.a, (EnumWithInnerClass[])null); - fail("Should throw NullPointerException"); - } catch (NullPointerException npe) { - // expected - } - - EnumFoo[] foos = {EnumFoo.a, EnumFoo.c, EnumFoo.d}; - EnumSet<EnumFoo> set = EnumSet.of(EnumFoo.c, foos); - assertEquals("size of set should be 1", 3, set.size()); - assertTrue("Should contain EnumFoo.a", set.contains(EnumFoo.a)); - assertTrue("Should contain EnumFoo.c", set.contains(EnumFoo.c)); - assertTrue("Should contain EnumFoo.d", set.contains(EnumFoo.d)); - - // test enum type with more than 64 elements - HugeEnumWithInnerClass[] hugeEnumArray = new HugeEnumWithInnerClass[] { - HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.c }; - EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a, - hugeEnumArray); - assertEquals(3, hugeEnumSet.size()); - - assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a)); - assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.c)); - - try { - EnumSet.of(HugeEnumWithInnerClass.a, (HugeEnumWithInnerClass[])null); - fail("Should throw NullPointerException"); - } catch (NullPointerException npe) { - // expected - } - - HugeEnumWithInnerClass[] huges = {HugeEnumWithInnerClass.a, HugeEnumWithInnerClass.c, HugeEnumWithInnerClass.d}; - EnumSet<HugeEnumWithInnerClass> hugeSet = EnumSet.of(HugeEnumWithInnerClass.c, huges); - assertEquals(3, hugeSet.size()); - assertTrue(hugeSet.contains(HugeEnumWithInnerClass.a)); - assertTrue(hugeSet.contains(HugeEnumWithInnerClass.c)); - assertTrue(hugeSet.contains(HugeEnumWithInnerClass.d)); - } - - /** - * java.util.EnumSet#range(E, E) - */ - public void test_Range_EE() { - try { - EnumSet.range(EnumWithInnerClass.c, null); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - - try { - EnumSet.range(null, EnumWithInnerClass.c); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - - try { - EnumSet.range(null, (EnumWithInnerClass) null); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - - try { - EnumSet.range(EnumWithInnerClass.b, EnumWithInnerClass.a); - fail("Should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - - EnumSet<EnumWithInnerClass> enumSet = EnumSet.range( - EnumWithInnerClass.a, EnumWithInnerClass.a); - assertEquals("Size of enumSet should be 1", 1, enumSet.size()); - - enumSet = EnumSet.range( - EnumWithInnerClass.a, EnumWithInnerClass.c); - assertEquals("Size of enumSet should be 3", 3, enumSet.size()); - - // test enum with more than 64 elements - try { - EnumSet.range(HugeEnumWithInnerClass.c, null); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - - try { - EnumSet.range(null, HugeEnumWithInnerClass.c); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - - try { - EnumSet.range(null, (HugeEnumWithInnerClass) null); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - - try { - EnumSet.range(HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.a); - fail("Should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - - EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.range( - HugeEnumWithInnerClass.a, HugeEnumWithInnerClass.a); - assertEquals(1, hugeEnumSet.size()); - - hugeEnumSet = EnumSet.range( - HugeEnumWithInnerClass.c, HugeEnumWithInnerClass.aa); - assertEquals(51, hugeEnumSet.size()); - - hugeEnumSet = EnumSet.range( - HugeEnumWithInnerClass.a, HugeEnumWithInnerClass.mm); - assertEquals(65, hugeEnumSet.size()); - - hugeEnumSet = EnumSet.range( - HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.mm); - assertEquals(64, hugeEnumSet.size()); - } - - /** - * java.util.EnumSet#clone() - */ - public void test_Clone() { - EnumSet<EnumFoo> enumSet = EnumSet.allOf(EnumFoo.class); - EnumSet<EnumFoo> clonedEnumSet = enumSet.clone(); - assertEquals(enumSet, clonedEnumSet); - assertNotSame(enumSet, clonedEnumSet); - assertTrue(clonedEnumSet.contains(EnumFoo.a)); - assertTrue(clonedEnumSet.contains(EnumFoo.b)); - assertEquals(64, clonedEnumSet.size()); - - // test enum type with more than 64 elements - EnumSet<HugeEnum> hugeEnumSet = EnumSet.allOf(HugeEnum.class); - EnumSet<HugeEnum> hugeClonedEnumSet = hugeEnumSet.clone(); - assertEquals(hugeEnumSet, hugeClonedEnumSet); - assertNotSame(hugeEnumSet, hugeClonedEnumSet); - assertTrue(hugeClonedEnumSet.contains(HugeEnum.a)); - assertTrue(hugeClonedEnumSet.contains(HugeEnum.b)); - assertEquals(65, hugeClonedEnumSet.size()); - - hugeClonedEnumSet.remove(HugeEnum.a); - assertEquals(64, hugeClonedEnumSet.size()); - assertFalse(hugeClonedEnumSet.contains(HugeEnum.a)); - assertEquals(65, hugeEnumSet.size()); - assertTrue(hugeEnumSet.contains(HugeEnum.a)); - } - - /** - * java.util.EnumSet#Serialization() - */ - public void test_serialization() throws Exception { - EnumSet<EnumFoo> set = EnumSet.allOf(EnumFoo.class); - SerializationTest.verifySelf(set); - } - - /** - * serialization/deserialization compatibility with RI. - */ - @SuppressWarnings( { "unchecked", "boxing" }) - public void testSerializationCompatibility() throws Exception { - EnumSet<EnumFoo> set = EnumSet.allOf(EnumFoo.class); - SerializationTest.verifyGolden(this, set); - } -} diff --git a/luni/src/test/java/tests/api/java/util/FormattableFlagsTest.java b/luni/src/test/java/tests/api/java/util/FormattableFlagsTest.java deleted file mode 100644 index 2aa4954..0000000 --- a/luni/src/test/java/tests/api/java/util/FormattableFlagsTest.java +++ /dev/null @@ -1,31 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.FormattableFlags; -import junit.framework.TestCase; - -public class FormattableFlagsTest extends TestCase { - - /** - * @test java.util.FormattableFlags ConstantFieldValues - */ - public void test_ConstantFieldValues() { - assertEquals(1, FormattableFlags.LEFT_JUSTIFY); - assertEquals(2, FormattableFlags.UPPERCASE); - assertEquals(4, FormattableFlags.ALTERNATE); - } -} diff --git a/luni/src/test/java/tests/api/java/util/HashMapTest.java b/luni/src/test/java/tests/api/java/util/HashMapTest.java deleted file mode 100644 index b37e813..0000000 --- a/luni/src/test/java/tests/api/java/util/HashMapTest.java +++ /dev/null @@ -1,558 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.*; - -import tests.support.Support_MapTest2; -import tests.support.Support_UnmodifiableCollectionTest; - -public class HashMapTest extends junit.framework.TestCase { - class MockMap extends AbstractMap { - public Set entrySet() { - return Collections.EMPTY_SET; - } - public int size(){ - return 0; - } - } - - private static class MockMapNull extends AbstractMap { - public Set entrySet() { - return null; - } - - public int size() { - return 10; - } - } - - HashMap hm; - - final static int hmSize = 1000; - - Object[] objArray; - - Object[] objArray2; - - /** - * java.util.HashMap#HashMap() - */ - public void test_Constructor() { - // Test for method java.util.HashMap() - new Support_MapTest2(new HashMap()).runTest(); - - HashMap hm2 = new HashMap(); - assertEquals("Created incorrect HashMap", 0, hm2.size()); - } - - /** - * java.util.HashMap#HashMap(int) - */ - public void test_ConstructorI() { - // Test for method java.util.HashMap(int) - HashMap hm2 = new HashMap(5); - assertEquals("Created incorrect HashMap", 0, hm2.size()); - try { - new HashMap(-1); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - HashMap empty = new HashMap(0); - assertNull("Empty hashmap access", empty.get("nothing")); - empty.put("something", "here"); - assertTrue("cannot get element", empty.get("something") == "here"); - } - - /** - * java.util.HashMap#HashMap(int, float) - */ - public void test_ConstructorIF() { - // Test for method java.util.HashMap(int, float) - HashMap hm2 = new HashMap(5, (float) 0.5); - assertEquals("Created incorrect HashMap", 0, hm2.size()); - try { - new HashMap(0, 0); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - HashMap empty = new HashMap(0, 0.75f); - assertNull("Empty hashtable access", empty.get("nothing")); - empty.put("something", "here"); - assertTrue("cannot get element", empty.get("something") == "here"); - } - - /** - * java.util.HashMap#HashMap(java.util.Map) - */ - public void test_ConstructorLjava_util_Map() { - // Test for method java.util.HashMap(java.util.Map) - Map myMap = new TreeMap(); - for (int counter = 0; counter < hmSize; counter++) - myMap.put(objArray2[counter], objArray[counter]); - HashMap hm2 = new HashMap(myMap); - for (int counter = 0; counter < hmSize; counter++) - assertTrue("Failed to construct correct HashMap", hm - .get(objArray2[counter]) == hm2.get(objArray2[counter])); - - Map mockMap = new MockMap(); - hm = new HashMap(mockMap); - assertEquals(hm, mockMap); - } - - /** - * java.util.HashMap#clear() - */ - public void test_clear() { - // Test for method void java.util.HashMap.clear() - hm.clear(); - assertEquals("Clear failed to reset size", 0, hm.size()); - for (int i = 0; i < hmSize; i++) - assertNull("Failed to clear all elements", - hm.get(objArray2[i])); - - } - - /** - * java.util.HashMap#clone() - */ - public void test_clone() { - // Test for method java.lang.Object java.util.HashMap.clone() - HashMap hm2 = (HashMap) hm.clone(); - assertTrue("Clone answered equivalent HashMap", hm2 != hm); - for (int counter = 0; counter < hmSize; counter++) - assertTrue("Clone answered unequal HashMap", hm - .get(objArray2[counter]) == hm2.get(objArray2[counter])); - - HashMap map = new HashMap(); - map.put("key", "value"); - // get the keySet() and values() on the original Map - Set keys = map.keySet(); - Collection values = map.values(); - assertEquals("values() does not work", - "value", values.iterator().next()); - assertEquals("keySet() does not work", - "key", keys.iterator().next()); - AbstractMap map2 = (AbstractMap) map.clone(); - map2.put("key", "value2"); - Collection values2 = map2.values(); - assertTrue("values() is identical", values2 != values); - // values() and keySet() on the cloned() map should be different - assertEquals("values() was not cloned", - "value2", values2.iterator().next()); - map2.clear(); - map2.put("key2", "value3"); - Set key2 = map2.keySet(); - assertTrue("keySet() is identical", key2 != keys); - assertEquals("keySet() was not cloned", - "key2", key2.iterator().next()); - - // regresion test for HARMONY-4603 - HashMap hashmap = new HashMap(); - MockClonable mock = new MockClonable(1); - hashmap.put(1, mock); - assertEquals(1, ((MockClonable) hashmap.get(1)).i); - HashMap hm3 = (HashMap)hashmap.clone(); - assertEquals(1, ((MockClonable) hm3.get(1)).i); - mock.i = 0; - assertEquals(0, ((MockClonable) hashmap.get(1)).i); - assertEquals(0, ((MockClonable) hm3.get(1)).i); - } - - /** - * java.util.HashMap#containsKey(java.lang.Object) - */ - public void test_containsKeyLjava_lang_Object() { - // Test for method boolean - // java.util.HashMap.containsKey(java.lang.Object) - assertTrue("Returned false for valid key", hm.containsKey(new Integer( - 876).toString())); - assertTrue("Returned true for invalid key", !hm.containsKey("KKDKDKD")); - - HashMap m = new HashMap(); - m.put(null, "test"); - assertTrue("Failed with null key", m.containsKey(null)); - assertTrue("Failed with missing key matching null hash", !m - .containsKey(new Integer(0))); - } - - /** - * java.util.HashMap#containsValue(java.lang.Object) - */ - public void test_containsValueLjava_lang_Object() { - // Test for method boolean - // java.util.HashMap.containsValue(java.lang.Object) - assertTrue("Returned false for valid value", hm - .containsValue(new Integer(875))); - assertTrue("Returned true for invalid valie", !hm - .containsValue(new Integer(-9))); - } - - /** - * java.util.HashMap#entrySet() - */ - public void test_entrySet() { - // Test for method java.util.Set java.util.HashMap.entrySet() - Set s = hm.entrySet(); - Iterator i = s.iterator(); - assertTrue("Returned set of incorrect size", hm.size() == s.size()); - while (i.hasNext()) { - Map.Entry m = (Map.Entry) i.next(); - assertTrue("Returned incorrect entry set", hm.containsKey(m - .getKey()) - && hm.containsValue(m.getValue())); - } - } - - /** - * java.util.HashMap#entrySet() - */ - public void test_entrySetEquals() { - Set s1 = hm.entrySet(); - Set s2 = new HashMap(hm).entrySet(); - assertEquals(s1, s2); - } - - /** - * java.util.HashMap#entrySet() - */ - public void test_removeFromViews() { - hm.put("A", null); - hm.put("B", null); - assertTrue(hm.keySet().remove("A")); - - Map<String, String> m2 = new HashMap<String, String>(); - m2.put("B", null); - assertTrue(hm.entrySet().remove(m2.entrySet().iterator().next())); - } - - /** - * java.util.HashMap#get(java.lang.Object) - */ - public void test_getLjava_lang_Object() { - // Test for method java.lang.Object - // java.util.HashMap.get(java.lang.Object) - assertNull("Get returned non-null for non existent key", - hm.get("T")); - hm.put("T", "HELLO"); - assertEquals("Get returned incorrect value for existing key", "HELLO", hm.get("T") - ); - - HashMap m = new HashMap(); - m.put(null, "test"); - assertEquals("Failed with null key", "test", m.get(null)); - assertNull("Failed with missing key matching null hash", m - .get(new Integer(0))); - - // Regression for HARMONY-206 - ReusableKey k = new ReusableKey(); - HashMap map = new HashMap(); - k.setKey(1); - map.put(k, "value1"); - - k.setKey(18); - assertNull(map.get(k)); - - k.setKey(17); - assertNull(map.get(k)); - } - - /** - * java.util.HashMap#isEmpty() - */ - public void test_isEmpty() { - // Test for method boolean java.util.HashMap.isEmpty() - assertTrue("Returned false for new map", new HashMap().isEmpty()); - assertTrue("Returned true for non-empty", !hm.isEmpty()); - } - - /** - * java.util.HashMap#keySet() - */ - public void test_keySet() { - // Test for method java.util.Set java.util.HashMap.keySet() - Set s = hm.keySet(); - assertTrue("Returned set of incorrect size()", s.size() == hm.size()); - for (int i = 0; i < objArray.length; i++) - assertTrue("Returned set does not contain all keys", s - .contains(objArray[i].toString())); - - HashMap m = new HashMap(); - m.put(null, "test"); - assertTrue("Failed with null key", m.keySet().contains(null)); - assertNull("Failed with null key", m.keySet().iterator().next()); - - Map map = new HashMap(101); - map.put(new Integer(1), "1"); - map.put(new Integer(102), "102"); - map.put(new Integer(203), "203"); - Iterator it = map.keySet().iterator(); - Integer remove1 = (Integer) it.next(); - it.hasNext(); - it.remove(); - Integer remove2 = (Integer) it.next(); - it.remove(); - ArrayList list = new ArrayList(Arrays.asList(new Integer[] { - new Integer(1), new Integer(102), new Integer(203) })); - list.remove(remove1); - list.remove(remove2); - assertTrue("Wrong result", it.next().equals(list.get(0))); - assertEquals("Wrong size", 1, map.size()); - assertTrue("Wrong contents", map.keySet().iterator().next().equals( - list.get(0))); - - Map map2 = new HashMap(101); - map2.put(new Integer(1), "1"); - map2.put(new Integer(4), "4"); - Iterator it2 = map2.keySet().iterator(); - Integer remove3 = (Integer) it2.next(); - Integer next; - if (remove3.intValue() == 1) - next = new Integer(4); - else - next = new Integer(1); - it2.hasNext(); - it2.remove(); - assertTrue("Wrong result 2", it2.next().equals(next)); - assertEquals("Wrong size 2", 1, map2.size()); - assertTrue("Wrong contents 2", map2.keySet().iterator().next().equals( - next)); - } - - /** - * java.util.HashMap#put(java.lang.Object, java.lang.Object) - */ - public void test_putLjava_lang_ObjectLjava_lang_Object() { - // Test for method java.lang.Object - // java.util.HashMap.put(java.lang.Object, java.lang.Object) - hm.put("KEY", "VALUE"); - assertEquals("Failed to install key/value pair", - "VALUE", hm.get("KEY")); - - HashMap m = new HashMap(); - m.put(new Short((short) 0), "short"); - m.put(null, "test"); - m.put(new Integer(0), "int"); - assertEquals("Failed adding to bucket containing null", "short", m.get( - new Short((short) 0))); - assertEquals("Failed adding to bucket containing null2", "int", m.get( - new Integer(0))); - } - - /** - * java.util.HashMap#putAll(java.util.Map) - */ - public void test_putAllLjava_util_Map() { - // Test for method void java.util.HashMap.putAll(java.util.Map) - HashMap hm2 = new HashMap(); - hm2.putAll(hm); - for (int i = 0; i < 1000; i++) - assertTrue("Failed to clear all elements", hm2.get( - new Integer(i).toString()).equals((new Integer(i)))); - - Map mockMap = new MockMap(); - hm2 = new HashMap(); - hm2.putAll(mockMap); - assertEquals("Size should be 0", 0, hm2.size()); - } - - /** - * java.util.HashMap#putAll(java.util.Map) - */ - public void test_putAllLjava_util_Map_Null() { - HashMap hashMap = new HashMap(); - try { - hashMap.putAll(new MockMapNull()); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected. - } - - try { - hashMap = new HashMap(new MockMapNull()); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected. - } - } - - public void test_putAllLjava_util_Map_Resize() { - Random rnd = new Random(666); - - Map<Integer,Integer> m1 = new HashMap<Integer, Integer>(); - int MID = 10000; - for (int i = 0; i < MID; i++) { - Integer j = rnd.nextInt(); - m1.put(j, j); - } - - Map<Integer,Integer> m2 = new HashMap<Integer, Integer>(); - int HI = 30000; - for (int i = MID; i < HI; i++) { - Integer j = rnd.nextInt(); - m2.put(j, j); - } - - m1.putAll(m2); - - rnd = new Random(666); - for (int i = 0; i < HI; i++) { - Integer j = rnd.nextInt(); - assertEquals(j, m1.get(j)); - } - } - - /** - * java.util.HashMap#remove(java.lang.Object) - */ - public void test_removeLjava_lang_Object() { - // Test for method java.lang.Object - // java.util.HashMap.remove(java.lang.Object) - int size = hm.size(); - Integer y = new Integer(9); - Integer x = ((Integer) hm.remove(y.toString())); - assertTrue("Remove returned incorrect value", x.equals(new Integer(9))); - assertNull("Failed to remove given key", hm.get(new Integer(9))); - assertTrue("Failed to decrement size", hm.size() == (size - 1)); - assertNull("Remove of non-existent key returned non-null", hm - .remove("LCLCLC")); - - HashMap m = new HashMap(); - m.put(null, "test"); - assertNull("Failed with same hash as null", - m.remove(new Integer(0))); - assertEquals("Failed with null key", "test", m.remove(null)); - } - - /** - * java.util.HashMap#size() - */ - public void test_size() { - // Test for method int java.util.HashMap.size() - assertTrue("Returned incorrect size", - hm.size() == (objArray.length + 2)); - } - - /** - * java.util.HashMap#values() - */ - public void test_values() { - // Test for method java.util.Collection java.util.HashMap.values() - Collection c = hm.values(); - assertTrue("Returned collection of incorrect size()", c.size() == hm - .size()); - for (int i = 0; i < objArray.length; i++) - assertTrue("Returned collection does not contain all keys", c - .contains(objArray[i])); - - HashMap myHashMap = new HashMap(); - for (int i = 0; i < 100; i++) - myHashMap.put(objArray2[i], objArray[i]); - Collection values = myHashMap.values(); - new Support_UnmodifiableCollectionTest( - "Test Returned Collection From HashMap.values()", values) - .runTest(); - values.remove(new Integer(0)); - assertTrue( - "Removing from the values collection should remove from the original map", - !myHashMap.containsValue(new Integer(0))); - - } - - static class ReusableKey { - private int key = 0; - - public void setKey(int key) { - this.key = key; - } - - public int hashCode() { - return key; - } - - public boolean equals(Object o) { - if (o == this) { - return true; - } - if (!(o instanceof ReusableKey)) { - return false; - } - return key == ((ReusableKey) o).key; - } - } - public void test_Map_Entry_hashCode() { - //Related to HARMONY-403 - HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(10); - Integer key = new Integer(1); - Integer val = new Integer(2); - map.put(key, val); - int expected = key.hashCode() ^ val.hashCode(); - assertEquals(expected, map.hashCode()); - key = new Integer(4); - val = new Integer(8); - map.put(key, val); - expected += key.hashCode() ^ val.hashCode(); - assertEquals(expected, map.hashCode()); - } - - class MockClonable implements Cloneable{ - public int i; - - public MockClonable(int i) { - this.i = i; - } - - @Override - protected Object clone() throws CloneNotSupportedException { - return new MockClonable(i); - } - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - objArray = new Object[hmSize]; - objArray2 = new Object[hmSize]; - for (int i = 0; i < objArray.length; i++) { - objArray[i] = new Integer(i); - objArray2[i] = objArray[i].toString(); - } - - hm = new HashMap(); - for (int i = 0; i < objArray.length; i++) - hm.put(objArray2[i], objArray[i]); - hm.put("test", null); - hm.put(null, "test"); - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - hm = null; - objArray = null; - objArray2 = null; - } -} diff --git a/luni/src/test/java/tests/api/java/util/HashSetTest.java b/luni/src/test/java/tests/api/java/util/HashSetTest.java deleted file mode 100644 index e4a65b7..0000000 --- a/luni/src/test/java/tests/api/java/util/HashSetTest.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; -import java.io.ObjectOutputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.Serializable; -import java.lang.reflect.Method; -import java.lang.reflect.InvocationTargetException; - -import org.apache.harmony.testframework.serialization.SerializationTest; - -public class HashSetTest extends junit.framework.TestCase { - - HashSet hs; - - Object[] objArray; - - /** - * java.util.HashSet#HashSet() - */ - public void test_Constructor() { - // Test for method java.util.HashSet() - HashSet hs2 = new HashSet(); - assertEquals("Created incorrect HashSet", 0, hs2.size()); - } - - /** - * java.util.HashSet#HashSet(int) - */ - public void test_ConstructorI() { - // Test for method java.util.HashSet(int) - HashSet hs2 = new HashSet(5); - assertEquals("Created incorrect HashSet", 0, hs2.size()); - try { - new HashSet(-1); - } catch (IllegalArgumentException e) { - return; - } - fail( - "Failed to throw IllegalArgumentException for capacity < 0"); - } - - /** - * java.util.HashSet#HashSet(int, float) - */ - public void test_ConstructorIF() { - // Test for method java.util.HashSet(int, float) - HashSet hs2 = new HashSet(5, (float) 0.5); - assertEquals("Created incorrect HashSet", 0, hs2.size()); - try { - new HashSet(0, 0); - } catch (IllegalArgumentException e) { - return; - } - fail( - "Failed to throw IllegalArgumentException for initial load factor <= 0"); - } - - /** - * java.util.HashSet#HashSet(java.util.Collection) - */ - public void test_ConstructorLjava_util_Collection() { - // Test for method java.util.HashSet(java.util.Collection) - HashSet hs2 = new HashSet(Arrays.asList(objArray)); - for (int counter = 0; counter < objArray.length; counter++) - assertTrue("HashSet does not contain correct elements", hs - .contains(objArray[counter])); - assertTrue("HashSet created from collection incorrect size", - hs2.size() == objArray.length); - - try { - new HashSet(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.HashSet#add(java.lang.Object) - */ - public void test_addLjava_lang_Object() { - // Test for method boolean java.util.HashSet.add(java.lang.Object) - int size = hs.size(); - hs.add(new Integer(8)); - assertTrue("Added element already contained by set", hs.size() == size); - hs.add(new Integer(-9)); - assertTrue("Failed to increment set size after add", - hs.size() == size + 1); - assertTrue("Failed to add element to set", hs.contains(new Integer(-9))); - } - - /** - * java.util.HashSet#clear() - */ - public void test_clear() { - // Test for method void java.util.HashSet.clear() - Set orgSet = (Set) hs.clone(); - hs.clear(); - Iterator i = orgSet.iterator(); - assertEquals("Returned non-zero size after clear", 0, hs.size()); - while (i.hasNext()) - assertTrue("Failed to clear set", !hs.contains(i.next())); - } - - /** - * java.util.HashSet#clone() - */ - public void test_clone() { - // Test for method java.lang.Object java.util.HashSet.clone() - HashSet hs2 = (HashSet) hs.clone(); - assertTrue("clone returned an equivalent HashSet", hs != hs2); - assertTrue("clone did not return an equal HashSet", hs.equals(hs2)); - } - - /** - * java.util.HashSet#contains(java.lang.Object) - */ - public void test_containsLjava_lang_Object() { - // Test for method boolean java.util.HashSet.contains(java.lang.Object) - assertTrue("Returned false for valid object", hs.contains(objArray[90])); - assertTrue("Returned true for invalid Object", !hs - .contains(new Object())); - - HashSet s = new HashSet(); - s.add(null); - assertTrue("Cannot handle null", s.contains(null)); - } - - /** - * java.util.HashSet#isEmpty() - */ - public void test_isEmpty() { - // Test for method boolean java.util.HashSet.isEmpty() - assertTrue("Empty set returned false", new HashSet().isEmpty()); - assertTrue("Non-empty set returned true", !hs.isEmpty()); - } - - /** - * java.util.HashSet#iterator() - */ - public void test_iterator() { - // Test for method java.util.Iterator java.util.HashSet.iterator() - Iterator i = hs.iterator(); - int x = 0; - while (i.hasNext()) { - assertTrue("Failed to iterate over all elements", hs.contains(i - .next())); - ++x; - } - assertTrue("Returned iteration of incorrect size", hs.size() == x); - - HashSet s = new HashSet(); - s.add(null); - assertNull("Cannot handle null", s.iterator().next()); - } - - /** - * java.util.HashSet#remove(java.lang.Object) - */ - public void test_removeLjava_lang_Object() { - // Test for method boolean java.util.HashSet.remove(java.lang.Object) - int size = hs.size(); - hs.remove(new Integer(98)); - assertTrue("Failed to remove element", !hs.contains(new Integer(98))); - assertTrue("Failed to decrement set size", hs.size() == size - 1); - - HashSet s = new HashSet(); - s.add(null); - assertTrue("Cannot handle null", s.remove(null)); - assertFalse(hs.remove(new Integer(-98))); - } - - /** - * java.util.HashSet#size() - */ - public void test_size() { - // Test for method int java.util.HashSet.size() - assertTrue("Returned incorrect size", hs.size() == (objArray.length + 1)); - hs.clear(); - assertEquals("Cleared set returned non-zero size", 0, hs.size()); - } - - /** - * java.util.HashSet#SerializationTest - */ - public void test_Serialization() throws Exception{ - HashSet<String> hs = new HashSet<String>(); - hs.add("hello"); - hs.add("world"); - SerializationTest.verifySelf(hs, comparator); - SerializationTest.verifyGolden(this, hs, comparator); - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - objArray = new Object[1000]; - for (int i = 0; i < objArray.length; i++) { - objArray[i] = new Integer(i); - } - - hs = new HashSet(); - for (int i = 0; i < objArray.length; i++) { - hs.add(objArray[i]); - } - - hs.add(null); - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - hs = null; - objArray = null; - } - - private static final SerializationTest.SerializableAssert comparator = new - SerializationTest.SerializableAssert() { - public void assertDeserialized(Serializable initial, Serializable deserialized) { - HashSet<String> initialHs = (HashSet<String>) initial; - HashSet<String> deseriaHs = (HashSet<String>) deserialized; - assertEquals("should be equal", initialHs.size(), deseriaHs.size()); - assertEquals("should be equal", initialHs, deseriaHs); - } - - }; -} diff --git a/luni/src/test/java/tests/api/java/util/HashtableTest.java b/luni/src/test/java/tests/api/java/util/HashtableTest.java deleted file mode 100644 index 9c97c7b..0000000 --- a/luni/src/test/java/tests/api/java/util/HashtableTest.java +++ /dev/null @@ -1,838 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.ConcurrentModificationException; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; -import java.util.TreeMap; -import java.util.Vector; -import java.util.Collections; - -import tests.api.java.util.HashMapTest.ReusableKey; -import tests.support.Support_MapTest2; -import tests.support.Support_UnmodifiableCollectionTest; - -public class HashtableTest extends junit.framework.TestCase { - - private Hashtable ht10; - - private Hashtable ht100; - - private Hashtable htfull; - - private Vector keyVector; - - private Vector elmVector; - - private String h10sVal; - - /** - * java.util.Hashtable#Hashtable() - */ - public void test_Constructor() { - // Test for method java.util.Hashtable() - new Support_MapTest2(new Hashtable()).runTest(); - - Hashtable h = new Hashtable(); - - assertEquals("Created incorrect hashtable", 0, h.size()); - } - - /** - * java.util.Hashtable#Hashtable(int) - */ - public void test_ConstructorI() { - // Test for method java.util.Hashtable(int) - Hashtable h = new Hashtable(9); - - assertEquals("Created incorrect hashtable", 0, h.size()); - - Hashtable empty = new Hashtable(0); - assertNull("Empty hashtable access", empty.get("nothing")); - empty.put("something", "here"); - assertTrue("cannot get element", empty.get("something") == "here"); - - try { - new Hashtable(-1); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - } - - /** - * java.util.Hashtable#Hashtable(int, float) - */ - public void test_ConstructorIF() { - // Test for method java.util.Hashtable(int, float) - Hashtable h = new java.util.Hashtable(10, 0.5f); - assertEquals("Created incorrect hashtable", 0, h.size()); - - Hashtable empty = new Hashtable(0, 0.75f); - assertNull("Empty hashtable access", empty.get("nothing")); - empty.put("something", "here"); - assertTrue("cannot get element", empty.get("something") == "here"); - - try { - new Hashtable(-1, 0.75f); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - new Hashtable(0, -0.75f); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - } - - /** - * java.util.Hashtable#Hashtable(java.util.Map) - */ - public void test_ConstructorLjava_util_Map() { - // Test for method java.util.Hashtable(java.util.Map) - Map map = new TreeMap(); - Object firstVal = "Gabba"; - Object secondVal = new Integer(5); - map.put("Gah", firstVal); - map.put("Ooga", secondVal); - Hashtable ht = new Hashtable(map); - assertTrue("a) Incorrect Hashtable constructed", - ht.get("Gah") == firstVal); - assertTrue("b) Incorrect Hashtable constructed", - ht.get("Ooga") == secondVal); - - try { - new Hashtable(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.Hashtable#Hashtable(java.util.Map) - */ - public void test_ConversionConstructorNullValue() { - Map<String, Void> map = Collections.singletonMap("Dog", null); - try { - new Hashtable<String, Void>(map); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - /** - * java.util.Hashtable#clear() - */ - public void test_clear() { - // Test for method void java.util.Hashtable.clear() - Hashtable h = hashtableClone(htfull); - h.clear(); - assertEquals("Hashtable was not cleared", 0, h.size()); - Enumeration el = h.elements(); - Enumeration keys = h.keys(); - assertTrue("Hashtable improperly cleared", !el.hasMoreElements() - && !(keys.hasMoreElements())); - } - - /** - * java.util.Hashtable#clone() - */ - public void test_clone() { - // Test for method java.lang.Object java.util.Hashtable.clone() - - Hashtable h = (Hashtable) htfull.clone(); - assertTrue("Clone different size than original", h.size() == htfull - .size()); - - Enumeration org = htfull.keys(); - Enumeration cpy = h.keys(); - - String okey, ckey; - while (org.hasMoreElements()) { - assertTrue("Key comparison failed", (okey = (String) org - .nextElement()).equals(ckey = (String) cpy.nextElement())); - assertTrue("Value comparison failed", ((String) htfull.get(okey)) - .equals((String) h.get(ckey))); - } - assertTrue("Copy has more keys than original", !cpy.hasMoreElements()); - } - - /** - * java.util.Hashtable#contains(java.lang.Object) - */ - public void test_containsLjava_lang_Object() { - // Test for method boolean - // java.util.Hashtable.contains(java.lang.Object) - assertTrue("Element not found", ht10.contains("Val 7")); - assertTrue("Invalid element found", !ht10.contains("ZZZZZZZZZZZZZZZZ")); - - try { - ht10.contains(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.Hashtable#containsKey(java.lang.Object) - */ - public void test_containsKeyLjava_lang_Object() { - // Test for method boolean - // java.util.Hashtable.containsKey(java.lang.Object) - - assertTrue("Failed to find key", htfull.containsKey("FKey 4")); - assertTrue("Failed to find key", !htfull.containsKey("FKey 99")); - - try { - htfull.containsKey(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.Hashtable#containsValue(java.lang.Object) - */ - public void test_containsValueLjava_lang_Object() { - // Test for method boolean - // java.util.Hashtable.containsValue(java.lang.Object) - Enumeration e = elmVector.elements(); - while (e.hasMoreElements()) - assertTrue("Returned false for valid value", ht10.containsValue(e - .nextElement())); - assertTrue("Returned true for invalid value", !ht10 - .containsValue(new Object())); - - try { - ht10.containsValue(null); - fail("NullPointerException expected"); - } catch (NullPointerException ee) { - //expected - } - } - - /** - * java.util.Hashtable#elements() - */ - public void test_elements() { - // Test for method java.util.Enumeration java.util.Hashtable.elements() - Enumeration elms = ht10.elements(); - int i = 0; - while (elms.hasMoreElements()) { - String s = (String) elms.nextElement(); - assertTrue("Missing key from enumeration", elmVector.contains(s)); - ++i; - } - - assertEquals("All keys not retrieved", 10, ht10.size()); - } - -// BEGIN android-removed -// implementation dependent -// /** -// * java.util.Hashtable#elements() -// */ -// public void test_elements_subtest0() { -// // this is the reference implementation behavior -// final Hashtable ht = new Hashtable(7); -// ht.put("1", "a"); -// // these three elements hash to the same bucket in a 7 element Hashtable -// ht.put("2", "b"); -// ht.put("9", "c"); -// ht.put("12", "d"); -// // Hashtable looks like: -// // 0: "1" -// // 1: "12" -> "9" -> "2" -// Enumeration en = ht.elements(); -// // cache the first entry -// en.hasMoreElements(); -// ht.remove("12"); -// ht.remove("9"); -// boolean exception = false; -// try { -// // cached "12" -// Object result = en.nextElement(); -// assertNull("unexpected: " + result, result); -// // next is removed "9" -// result = en.nextElement(); -// assertNull("unexpected: " + result, result); -// result = en.nextElement(); -// assertTrue("unexpected: " + result, "b".equals(result)); -// } catch (NoSuchElementException e) { -// exception = true; -// } -// assertTrue("unexpected NoSuchElementException", !exception); -// } -// END android-removed - - /** - * java.util.Hashtable#entrySet() - */ - public void test_entrySet() { - // Test for method java.util.Set java.util.Hashtable.entrySet() - Set s = ht10.entrySet(); - Set s2 = new HashSet(); - Iterator i = s.iterator(); - while (i.hasNext()) - s2.add(((Map.Entry) i.next()).getValue()); - Enumeration e = elmVector.elements(); - while (e.hasMoreElements()) - assertTrue("Returned incorrect entry set", s2.contains(e - .nextElement())); -// BEGIN android-removed -// implementation dependent -// assertEquals("Not synchronized", -// "java.util.Collections$SynchronizedSet", s.getClass().getName()); -// END android-removed - - boolean exception = false; - try { - ((Map.Entry) ht10.entrySet().iterator().next()).setValue(null); - } catch (NullPointerException e1) { - exception = true; - } - assertTrue( - "Should not be able to assign null to a Hashtable entrySet() Map.Entry", - exception); - } - - /** - * java.util.Hashtable#equals(java.lang.Object) - */ - public void test_equalsLjava_lang_Object() { - // Test for method boolean java.util.Hashtable.equals(java.lang.Object) - Hashtable h = hashtableClone(ht10); - assertTrue("Returned false for equal tables", ht10.equals(h)); - assertTrue("Returned true for unequal tables", !ht10.equals(htfull)); - } - - /** - * java.util.Hashtable#get(java.lang.Object) - */ - public void test_getLjava_lang_Object() { - // Test for method java.lang.Object - // java.util.Hashtable.get(java.lang.Object) - Hashtable h = hashtableClone(htfull); - assertEquals("Could not retrieve element", "FVal 2", ((String) h.get("FKey 2")) - ); - -// BEGIN android-removed -// implementation dependent -// // Regression for HARMONY-262 -// ReusableKey k = new ReusableKey(); -// Hashtable h2 = new Hashtable(); -// k.setKey(1); -// h2.put(k, "value1"); -// -// k.setKey(13); -// assertNull(h2.get(k)); -// -// k.setKey(12); -// assertNull(h2.get(k)); -// -// try { -// h2.get(null); -// fail("NullPointerException expected"); -// } catch (NullPointerException e) { -// //expected -// } -// END android-removed - } - - /** - * java.util.Hashtable#hashCode() - */ - public void test_hashCode() { - // Test for method int java.util.Hashtable.hashCode() - Set entrySet = ht10.entrySet(); - Iterator iterator = entrySet.iterator(); - int expectedHash; - for (expectedHash = 0; iterator.hasNext(); expectedHash += iterator - .next().hashCode()) - ; - assertTrue("Incorrect hashCode returned. Wanted: " + expectedHash - + " got: " + ht10.hashCode(), expectedHash == ht10.hashCode()); - } - - /** - * java.util.Hashtable#isEmpty() - */ - public void test_isEmpty() { - // Test for method boolean java.util.Hashtable.isEmpty() - - assertTrue("isEmpty returned incorrect value", !ht10.isEmpty()); - assertTrue("isEmpty returned incorrect value", - new java.util.Hashtable().isEmpty()); - - final Hashtable ht = new Hashtable(); - ht.put("0", ""); - Thread t1 = new Thread() { - public void run() { - while (!ht.isEmpty()) - ; - ht.put("final", ""); - } - }; - t1.start(); - for (int i = 1; i < 10000; i++) { - synchronized (ht) { - ht.remove(String.valueOf(i - 1)); - ht.put(String.valueOf(i), ""); - } - int size; - if ((size = ht.size()) != 1) { - String result = "Size is not 1: " + size + " " + ht; - // terminate the thread - ht.clear(); - fail(result); - } - } - // terminate the thread - ht.clear(); - } - - /** - * java.util.Hashtable#keys() - */ - public void test_keys() { - // Test for method java.util.Enumeration java.util.Hashtable.keys() - - Enumeration keys = ht10.keys(); - int i = 0; - while (keys.hasMoreElements()) { - String s = (String) keys.nextElement(); - assertTrue("Missing key from enumeration", keyVector.contains(s)); - ++i; - } - - assertEquals("All keys not retrieved", 10, ht10.size()); - } - - /** - * java.util.Hashtable#keys() - */ - public void test_keys_subtest0() { - // this is the reference implementation behavior - final Hashtable ht = new Hashtable(3); - ht.put("initial", ""); - Enumeration en = ht.keys(); - en.hasMoreElements(); - ht.remove("initial"); - boolean exception = false; - try { - Object result = en.nextElement(); - assertTrue("unexpected: " + result, "initial".equals(result)); - } catch (NoSuchElementException e) { - exception = true; - } - assertTrue("unexpected NoSuchElementException", !exception); - } - - /** - * java.util.Hashtable#keySet() - */ - public void test_keySet() { - // Test for method java.util.Set java.util.Hashtable.keySet() - Set s = ht10.keySet(); - Enumeration e = keyVector.elements(); - while (e.hasMoreElements()) - assertTrue("Returned incorrect key set", s - .contains(e.nextElement())); - -// BEGIN android-removed -// implementation dependent -// assertEquals("Not synchronized", -// "java.util.Collections$SynchronizedSet", s.getClass().getName()); -// END android-removed - - Map map = new Hashtable(101); - map.put(new Integer(1), "1"); - map.put(new Integer(102), "102"); - map.put(new Integer(203), "203"); - Iterator it = map.keySet().iterator(); - Integer remove1 = (Integer) it.next(); - it.remove(); - Integer remove2 = (Integer) it.next(); - it.remove(); - ArrayList list = new ArrayList(Arrays.asList(new Integer[] { - new Integer(1), new Integer(102), new Integer(203) })); - list.remove(remove1); - list.remove(remove2); - assertTrue("Wrong result", it.next().equals(list.get(0))); - assertEquals("Wrong size", 1, map.size()); - assertTrue("Wrong contents", map.keySet().iterator().next().equals( - list.get(0))); - - Map map2 = new Hashtable(101); - map2.put(new Integer(1), "1"); - map2.put(new Integer(4), "4"); - Iterator it2 = map2.keySet().iterator(); - Integer remove3 = (Integer) it2.next(); - Integer next; - if (remove3.intValue() == 1) - next = new Integer(4); - else - next = new Integer(1); - it2.hasNext(); - it2.remove(); - assertTrue("Wrong result 2", it2.next().equals(next)); - assertEquals("Wrong size 2", 1, map2.size()); - assertTrue("Wrong contents 2", map2.keySet().iterator().next().equals( - next)); - } - - /** - * java.util.Hashtable#keySet() - */ - public void test_keySet_subtest0() { - Set s1 = ht10.keySet(); - assertTrue("should contain key", s1.remove("Key 0")); - assertTrue("should not contain key", !s1.remove("Key 0")); - - final int iterations = 10000; - final Hashtable ht = new Hashtable(); - Thread t1 = new Thread() { - public void run() { - for (int i = 0; i < iterations; i++) { - ht.put(String.valueOf(i), ""); - ht.remove(String.valueOf(i)); - } - } - }; - t1.start(); - Set set = ht.keySet(); - for (int i = 0; i < iterations; i++) { - Iterator it = set.iterator(); - try { - it.next(); - it.remove(); - int size; - // ensure removing with the iterator doesn't corrupt the - // Hashtable - if ((size = ht.size()) < 0) { - fail("invalid size: " + size); - } - } catch (NoSuchElementException e) { - } catch (ConcurrentModificationException e) { - } - } - } - -// BEGIN android-removed -// implementation dependent -// /** -// * java.util.Hashtable#keySet() -// */ -// public void test_keySet_subtest1() { -// // this is the reference implementation behavior -// final Hashtable ht = new Hashtable(7); -// ht.put("1", "a"); -// // these three elements hash to the same bucket in a 7 element Hashtable -// ht.put("2", "b"); -// ht.put("9", "c"); -// ht.put("12", "d"); -// // Hashtable looks like: -// // 0: "1" -// // 1: "12" -> "9" -> "2" -// Enumeration en = ht.elements(); -// // cache the first entry -// en.hasMoreElements(); -// Iterator it = ht.keySet().iterator(); -// // this is mostly a copy of the test in test_elements_subtest0() -// // test removing with the iterator does not null the values -// while (it.hasNext()) { -// String key = (String) it.next(); -// if ("12".equals(key) || "9".equals(key)) { -// it.remove(); -// } -// } -// it.remove(); -// boolean exception = false; -// try { -// // cached "12" -// Object result = en.nextElement(); -// assertTrue("unexpected: " + result, "d".equals(result)); -// // next is removed "9" -// result = en.nextElement(); -// assertTrue("unexpected: " + result, "c".equals(result)); -// result = en.nextElement(); -// assertTrue("unexpected: " + result, "b".equals(result)); -// } catch (NoSuchElementException e) { -// exception = true; -// } -// assertTrue("unexpected NoSuchElementException", !exception); -// } -// END android-removed - - /** - * java.util.Hashtable#put(java.lang.Object, java.lang.Object) - */ - public void test_putLjava_lang_ObjectLjava_lang_Object() { - // Test for method java.lang.Object - // java.util.Hashtable.put(java.lang.Object, java.lang.Object) - Hashtable h = hashtableClone(ht100); - Integer key = new Integer(100); - h.put("Value 100", key); - assertTrue("Key/Value not inserted", h.size() == 1 && (h.contains(key))); - - // Put into "full" table - h = hashtableClone(htfull); - h.put("Value 100", key); - assertTrue("Key/Value not inserted into full table", h.size() == 8 - && (h.contains(key))); - - try { - h.put(null, key); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - - try { - h.put("Value 100", null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.Hashtable#putAll(java.util.Map) - */ - public void test_putAllLjava_util_Map() { - // Test for method void java.util.Hashtable.putAll(java.util.Map) - Hashtable h = new Hashtable(); - h.putAll(ht10); - Enumeration e = keyVector.elements(); - while (e.hasMoreElements()) { - Object x = e.nextElement(); - assertTrue("Failed to put all elements", h.get(x).equals( - ht10.get(x))); - } - - try { - h.putAll(null); - fail("NullPointerException expected"); - } catch (NullPointerException ee) { - //expected - } - } - - /** - * java.util.Hashtable#remove(java.lang.Object) - */ - public void test_removeLjava_lang_Object() { - // Test for method java.lang.Object - // java.util.Hashtable.remove(java.lang.Object) - Hashtable h = hashtableClone(htfull); - Object k = h.remove("FKey 0"); - assertTrue("Remove failed", !h.containsKey("FKey 0") || k == null); - assertNull(h.remove("FKey 0")); - - try { - h.remove(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.Hashtable#size() - */ - public void test_size() { - // Test for method int java.util.Hashtable.size() - assertTrue("Returned invalid size", ht10.size() == 10 - && (ht100.size() == 0)); - - final Hashtable ht = new Hashtable(); - ht.put("0", ""); - Thread t1 = new Thread() { - public void run() { - while (ht.size() > 0) - ; - ht.put("final", ""); - } - }; - t1.start(); - for (int i = 1; i < 10000; i++) { - synchronized (ht) { - ht.remove(String.valueOf(i - 1)); - ht.put(String.valueOf(i), ""); - } - int size; - if ((size = ht.size()) != 1) { - String result = "Size is not 1: " + size + " " + ht; - // terminate the thread - ht.clear(); - fail(result); - } - } - // terminate the thread - ht.clear(); - } - - /** - * java.util.Hashtable#toString() - */ - public void test_toString() { - // Test for method java.lang.String java.util.Hashtable.toString() - Hashtable h = new Hashtable(); - assertEquals("Incorrect toString for Empty table", - "{}", h.toString()); - - h.put("one", "1"); - h.put("two", h); - h.put(h, "3"); - h.put(h, h); - String result = h.toString(); - assertTrue("should contain self ref", result.indexOf("(this") > -1); - } - - /** - * java.util.Hashtable#values() - */ - public void test_values() { - // Test for method java.util.Collection java.util.Hashtable.values() - Collection c = ht10.values(); - Enumeration e = elmVector.elements(); - while (e.hasMoreElements()) - assertTrue("Returned incorrect values", c.contains(e.nextElement())); - -// BEGIN android-removed -// implementation dependent -// assertEquals("Not synchronized", -// "java.util.Collections$SynchronizedCollection", c.getClass().getName()); -// END android-removed - - Hashtable myHashtable = new Hashtable(); - for (int i = 0; i < 100; i++) - myHashtable.put(new Integer(i), new Integer(i)); - Collection values = myHashtable.values(); - new Support_UnmodifiableCollectionTest( - "Test Returned Collection From Hashtable.values()", values) - .runTest(); - values.remove(new Integer(0)); - assertTrue( - "Removing from the values collection should remove from the original map", - !myHashtable.containsValue(new Integer(0))); - } - - /** - * Regression Test for JIRA 2181 - */ - public void test_entrySet_remove() - { - Hashtable<String,String> hashtable = new Hashtable<String,String>(); - hashtable.put("my.nonexistent.prop", "AAA"); - hashtable.put( "parse.error", "BBB" ); - Iterator<Map.Entry<String,String>> iterator = - hashtable.entrySet().iterator(); - while(iterator.hasNext()) - { - Map.Entry entry = iterator.next(); - final Object value = entry.getValue(); - if(value.equals("AAA")) - { - iterator.remove(); - } - } - assertFalse(hashtable.containsKey("my.nonexistent.prop")); - } - - class Mock_Hashtable extends Hashtable { - boolean flag = false; - - public Mock_Hashtable(int i) { - super(i); - } - - @Override - protected void rehash() { - flag = true; - super.rehash(); - } - - public boolean isRehashed() { - return flag; - } - } - - public void test_rehash() { - Mock_Hashtable mht = new Mock_Hashtable(5); - - assertFalse(mht.isRehashed()); - for(int i = 0; i < 10; i++) { - mht.put(i, "New value"); - } - assertTrue(mht.isRehashed()); - } - - protected Hashtable hashtableClone(Hashtable s) { - return (Hashtable) s.clone(); - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - - ht10 = new Hashtable(10); - ht100 = new Hashtable(100); - htfull = new Hashtable(10); - keyVector = new Vector(10); - elmVector = new Vector(10); - - for (int i = 0; i < 10; i++) { - ht10.put("Key " + i, "Val " + i); - keyVector.addElement("Key " + i); - elmVector.addElement("Val " + i); - } - - for (int i = 0; i < 7; i++) - htfull.put("FKey " + i, "FVal " + i); - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - ht10 = null; - ht100 = null; - htfull = null; - keyVector = null; - elmVector = null; - } -} diff --git a/luni/src/test/java/tests/api/java/util/IdentityHashMapTest.java b/luni/src/test/java/tests/api/java/util/IdentityHashMapTest.java deleted file mode 100644 index 3bf1257..0000000 --- a/luni/src/test/java/tests/api/java/util/IdentityHashMapTest.java +++ /dev/null @@ -1,494 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.io.Serializable; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.IdentityHashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -import tests.support.Support_MapTest2; - -import org.apache.harmony.testframework.serialization.SerializationTest; - -public class IdentityHashMapTest extends junit.framework.TestCase { - private static final String ID = "hello"; - - class MockMap extends AbstractMap { - public Set entrySet() { - return null; - } - public int size(){ - return 0; - } - } - /* - * TODO: change all the statements testing the keys and values with equals() - * method to check for reference equality instead - */ - - IdentityHashMap hm; - - final static int hmSize = 1000; - - Object[] objArray; - - Object[] objArray2; - - /** - * java.util.IdentityHashMap#IdentityHashMap() - */ - public void test_Constructor() { - // Test for method java.util.IdentityHashMap() - new Support_MapTest2(new IdentityHashMap()).runTest(); - - IdentityHashMap hm2 = new IdentityHashMap(); - assertEquals("Created incorrect IdentityHashMap", 0, hm2.size()); - } - - /** - * java.util.IdentityHashMap#IdentityHashMap(int) - */ - public void test_ConstructorI() { - // Test for method java.util.IdentityHashMap(int) - IdentityHashMap hm2 = new IdentityHashMap(5); - assertEquals("Created incorrect IdentityHashMap", 0, hm2.size()); - try { - new IdentityHashMap(-1); - fail("Failed to throw IllegalArgumentException for initial capacity < 0"); - } catch (IllegalArgumentException e) { - //expected - } - - IdentityHashMap empty = new IdentityHashMap(0); - assertNull("Empty IdentityHashMap access", empty.get("nothing")); - empty.put("something", "here"); - assertTrue("cannot get element", empty.get("something") == "here"); - } - - /** - * java.util.IdentityHashMap#IdentityHashMap(java.util.Map) - */ - public void test_ConstructorLjava_util_Map() { - // Test for method java.util.IdentityHashMap(java.util.Map) - Map myMap = new TreeMap(); - for (int counter = 0; counter < hmSize; counter++) - myMap.put(objArray2[counter], objArray[counter]); - IdentityHashMap hm2 = new IdentityHashMap(myMap); - for (int counter = 0; counter < hmSize; counter++) - assertTrue("Failed to construct correct IdentityHashMap", hm - .get(objArray2[counter]) == hm2.get(objArray2[counter])); - - Map mockMap = new MockMap(); - hm2 = new IdentityHashMap(mockMap); - assertEquals("Size should be 0", 0, hm2.size()); - - try { - new IdentityHashMap(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.IdentityHashMap#clear() - */ - public void test_clear() { - // Test for method void java.util.IdentityHashMap.clear() - hm.clear(); - assertEquals("Clear failed to reset size", 0, hm.size()); - for (int i = 0; i < hmSize; i++) - assertNull("Failed to clear all elements", - hm.get(objArray2[i])); - - } - - /** - * java.util.IdentityHashMap#clone() - */ - public void test_clone() { - // Test for method java.lang.Object java.util.IdentityHashMap.clone() - IdentityHashMap hm2 = (IdentityHashMap) hm.clone(); - assertTrue("Clone answered equivalent IdentityHashMap", hm2 != hm); - for (int counter = 0; counter < hmSize; counter++) - assertTrue("Clone answered unequal IdentityHashMap", hm - .get(objArray2[counter]) == hm2.get(objArray2[counter])); - - IdentityHashMap map = new IdentityHashMap(); - map.put("key", "value"); - // get the keySet() and values() on the original Map - Set keys = map.keySet(); - Collection values = map.values(); - assertEquals("values() does not work", - "value", values.iterator().next()); - assertEquals("keySet() does not work", - "key", keys.iterator().next()); - AbstractMap map2 = (AbstractMap) map.clone(); - map2.put("key", "value2"); - Collection values2 = map2.values(); - assertTrue("values() is identical", values2 != values); - // values() and keySet() on the cloned() map should be different - assertEquals("values() was not cloned", - "value2", values2.iterator().next()); - map2.clear(); - map2.put("key2", "value3"); - Set key2 = map2.keySet(); - assertTrue("keySet() is identical", key2 != keys); - assertEquals("keySet() was not cloned", - "key2", key2.iterator().next()); - } - - /** - * java.util.IdentityHashMap#containsKey(java.lang.Object) - */ - public void test_containsKeyLjava_lang_Object() { - // Test for method boolean - // java.util.IdentityHashMap.containsKey(java.lang.Object) - assertTrue("Returned false for valid key", hm - .containsKey(objArray2[23])); - assertTrue("Returned true for copy of valid key", !hm - .containsKey(new Integer(23).toString())); - assertTrue("Returned true for invalid key", !hm.containsKey("KKDKDKD")); - - IdentityHashMap m = new IdentityHashMap(); - m.put(null, "test"); - assertTrue("Failed with null key", m.containsKey(null)); - assertTrue("Failed with missing key matching null hash", !m - .containsKey(new Integer(0))); - } - - /** - * java.util.IdentityHashMap#containsValue(java.lang.Object) - */ - public void test_containsValueLjava_lang_Object() { - // Test for method boolean - // java.util.IdentityHashMap.containsValue(java.lang.Object) - assertTrue("Returned false for valid value", hm - .containsValue(objArray[19])); - assertTrue("Returned true for invalid valie", !hm - .containsValue(new Integer(-9))); - } - - /** - * java.util.IdentityHashMap#entrySet() - */ - public void test_entrySet() { - // Test for method java.util.Set java.util.IdentityHashMap.entrySet() - Set s = hm.entrySet(); - Iterator i = s.iterator(); - assertTrue("Returned set of incorrect size", hm.size() == s.size()); - while (i.hasNext()) { - Map.Entry m = (Map.Entry) i.next(); - assertTrue("Returned incorrect entry set", hm.containsKey(m - .getKey()) - && hm.containsValue(m.getValue())); - } - } - - /** - * java.util.IdentityHashMap#get(java.lang.Object) - */ - public void test_getLjava_lang_Object() { - // Test for method java.lang.Object - // java.util.IdentityHashMap.get(java.lang.Object) - assertNull("Get returned non-null for non existent key", - hm.get("T")); - hm.put("T", "HELLO"); - assertEquals("Get returned incorecct value for existing key", "HELLO", hm.get("T") - ); - - IdentityHashMap m = new IdentityHashMap(); - m.put(null, "test"); - assertEquals("Failed with null key", "test", m.get(null)); - assertNull("Failed with missing key matching null hash", m - .get(new Integer(0))); - } - - /** - * java.util.IdentityHashMap#isEmpty() - */ - public void test_isEmpty() { - // Test for method boolean java.util.IdentityHashMap.isEmpty() - assertTrue("Returned false for new map", new IdentityHashMap() - .isEmpty()); - assertTrue("Returned true for non-empty", !hm.isEmpty()); - } - - /** - * java.util.IdentityHashMap#keySet() - */ - public void test_keySet() { - // Test for method java.util.Set java.util.IdentityHashMap.keySet() - Set s = hm.keySet(); - assertTrue("Returned set of incorrect size()", s.size() == hm.size()); - for (int i = 0; i < objArray.length; i++) { - assertTrue("Returned set does not contain all keys", s - .contains(objArray2[i])); - } - - IdentityHashMap m = new IdentityHashMap(); - m.put(null, "test"); - assertTrue("Failed with null key", m.keySet().contains(null)); - assertNull("Failed with null key", m.keySet().iterator().next()); - - Map map = new IdentityHashMap(101); - map.put(new Integer(1), "1"); - map.put(new Integer(102), "102"); - map.put(new Integer(203), "203"); - Iterator it = map.keySet().iterator(); - Integer remove1 = (Integer) it.next(); - it.hasNext(); - it.remove(); - Integer remove2 = (Integer) it.next(); - it.remove(); - ArrayList list = new ArrayList(Arrays.asList(new Integer[] { - new Integer(1), new Integer(102), new Integer(203) })); - list.remove(remove1); - list.remove(remove2); - assertTrue("Wrong result", it.next().equals(list.get(0))); - assertEquals("Wrong size", 1, map.size()); - assertTrue("Wrong contents", map.keySet().iterator().next().equals( - list.get(0))); - - Map map2 = new IdentityHashMap(101); - map2.put(new Integer(1), "1"); - map2.put(new Integer(4), "4"); - Iterator it2 = map2.keySet().iterator(); - Integer remove3 = (Integer) it2.next(); - Integer next; - if (remove3.intValue() == 1) - next = new Integer(4); - else - next = new Integer(1); - it2.hasNext(); - it2.remove(); - assertTrue("Wrong result 2", it2.next().equals(next)); - assertEquals("Wrong size 2", 1, map2.size()); - assertTrue("Wrong contents 2", map2.keySet().iterator().next().equals( - next)); - } - - /** - * java.util.IdentityHashMap#put(java.lang.Object, java.lang.Object) - */ - public void test_putLjava_lang_ObjectLjava_lang_Object() { - // Test for method java.lang.Object - // java.util.IdentityHashMap.put(java.lang.Object, java.lang.Object) - hm.put("KEY", "VALUE"); - assertEquals("Failed to install key/value pair", - "VALUE", hm.get("KEY")); - - IdentityHashMap m = new IdentityHashMap(); - Short s0 = new Short((short) 0); - m.put(s0, "short"); - m.put(null, "test"); - Integer i0 = new Integer(0); - m.put(i0, "int"); - assertEquals("Failed adding to bucket containing null", - "short", m.get(s0)); - assertEquals("Failed adding to bucket containing null2", "int", m.get(i0) - ); - } - - /** - * java.util.IdentityHashMap#putAll(java.util.Map) - */ - public void test_putAllLjava_util_Map() { - // Test for method void java.util.IdentityHashMap.putAll(java.util.Map) - IdentityHashMap hm2 = new IdentityHashMap(); - hm2.putAll(hm); - for (int i = 0; i < 1000; i++) - assertTrue("Failed to clear all elements", hm2.get(objArray2[i]) - .equals((new Integer(i)))); - - hm2 = new IdentityHashMap(); - Map mockMap = new MockMap(); - hm2.putAll(mockMap); - assertEquals("Size should be 0", 0, hm2.size()); - - try { - hm2.putAll(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.IdentityHashMap#remove(java.lang.Object) - */ - public void test_removeLjava_lang_Object() { - // Test for method java.lang.Object - // java.util.IdentityHashMap.remove(java.lang.Object) - int size = hm.size(); - Integer x = ((Integer) hm.remove(objArray2[9])); - assertTrue("Remove returned incorrect value", x.equals(new Integer(9))); - assertNull("Failed to remove given key", hm.get(objArray2[9])); - assertTrue("Failed to decrement size", hm.size() == (size - 1)); - assertNull("Remove of non-existent key returned non-null", hm - .remove("LCLCLC")); - - IdentityHashMap m = new IdentityHashMap(); - m.put(null, "test"); - assertNull("Failed with same hash as null", - m.remove(objArray[0])); - assertEquals("Failed with null key", "test", m.remove(null)); - } - - /** - * java.util.IdentityHashMap#size() - */ - public void test_size() { - // Test for method int java.util.IdentityHashMap.size() - assertEquals("Returned incorrect size, ", (objArray.length + 2), hm - .size()); - } - - /** - * java.util.IdentityHashMap#equals(java.lang.Object) - */ - public void test_equalsLjava_lang_Object() { - IdentityHashMap mapOne = new IdentityHashMap(); - IdentityHashMap mapTwo = new IdentityHashMap(); - IdentityHashMap mapThree = new IdentityHashMap(); - IdentityHashMap mapFour = new IdentityHashMap(); - - String one = "one"; - String alsoOne = new String(one); // use the new operator to ensure a - // new reference is constructed - String two = "two"; - String alsoTwo = new String(two); // use the new operator to ensure a - // new reference is constructed - - mapOne.put(one, two); - mapFour.put(one, two); - - // these two are not equal to the above two - mapTwo.put(alsoOne, two); - mapThree.put(one, alsoTwo); - - assertEquals("failure of equality of IdentityHashMaps", mapOne, mapFour); - assertTrue("failure of non-equality of IdentityHashMaps one and two", - !mapOne.equals(mapTwo)); - assertTrue("failure of non-equality of IdentityHashMaps one and three", - !mapOne.equals(mapThree)); - assertTrue("failure of non-equality of IdentityHashMaps two and three", - !mapTwo.equals(mapThree)); - - HashMap hashMapTwo = new HashMap(); - HashMap hashMapThree = new HashMap(); - hashMapTwo.put(alsoOne, two); - hashMapThree.put(one, alsoTwo); - - assertTrue( - "failure of non-equality of IdentityHashMaps one and Hashmap two", - !mapOne.equals(hashMapTwo)); - assertTrue( - "failure of non-equality of IdentityHashMaps one and Hashmap three", - !mapOne.equals(hashMapThree)); - } - - /** - * java.util.IdentityHashMap#values() - */ - public void test_values() { - // Test for method java.util.Collection - // java.util.IdentityHashMap.values() - Collection c = hm.values(); - assertTrue("Returned collection of incorrect size()", c.size() == hm - .size()); - for (int i = 0; i < objArray.length; i++) - assertTrue("Returned collection does not contain all keys", c - .contains(objArray[i])); - - IdentityHashMap myIdentityHashMap = new IdentityHashMap(); - for (int i = 0; i < 100; i++) - myIdentityHashMap.put(objArray2[i], objArray[i]); - Collection values = myIdentityHashMap.values(); - values.remove(objArray[0]); - assertTrue( - "Removing from the values collection should remove from the original map", - !myIdentityHashMap.containsValue(objArray2[0])); - - } - - /** - * java.util.IdentityHashMap#Serialization() - */ - public void test_Serialization() throws Exception { - IdentityHashMap<String, String> map = new IdentityHashMap<String, String>(); - map.put(ID, "world"); - // BEGIN android-added - // Regression test for null key in serialized IdentityHashMap (1178549) - // Together with this change the IdentityHashMap.golden.ser resource - // was replaced by a version that contains a map with a null key. - map.put(null, "null"); - // END android-added - SerializationTest.verifySelf(map, comparator); - SerializationTest.verifyGolden(this, map, comparator); - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - objArray = new Object[hmSize]; - objArray2 = new Object[hmSize]; - for (int i = 0; i < objArray.length; i++) { - objArray[i] = new Integer(i); - // android-changed: the containsKey test requires unique strings. - objArray2[i] = new String(objArray[i].toString()); - } - - hm = new IdentityHashMap(); - for (int i = 0; i < objArray.length; i++) - hm.put(objArray2[i], objArray[i]); - hm.put("test", null); - hm.put(null, "test"); - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - objArray = null; - objArray2 = null; - hm = null; - } - - private static final SerializationTest.SerializableAssert comparator = new - SerializationTest.SerializableAssert() { - - public void assertDeserialized(Serializable initial, Serializable deserialized) { - IdentityHashMap<String, String> initialMap = (IdentityHashMap<String, String>) initial; - IdentityHashMap<String, String> deseriaMap = (IdentityHashMap<String, String>) deserialized; - assertEquals("should be equal", initialMap.size(), deseriaMap.size()); - } - - }; -} diff --git a/luni/src/test/java/tests/api/java/util/InvalidPropertiesFormatExceptionTest.java b/luni/src/test/java/tests/api/java/util/InvalidPropertiesFormatExceptionTest.java deleted file mode 100644 index 0b144a4..0000000 --- a/luni/src/test/java/tests/api/java/util/InvalidPropertiesFormatExceptionTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.io.NotSerializableException; -import java.util.InvalidPropertiesFormatException; - -import org.apache.harmony.testframework.serialization.SerializationTest; - -public class InvalidPropertiesFormatExceptionTest extends - junit.framework.TestCase { - - /** - * java.util.InvalidPropertiesFormatException#SerializationTest() - */ - public void test_Serialization() throws Exception { - InvalidPropertiesFormatException ipfe = new InvalidPropertiesFormatException( - "Hey, this is InvalidPropertiesFormatException"); - try { - SerializationTest.verifySelf(ipfe); - } catch (NotSerializableException e) { - // expected - } - } - -} diff --git a/luni/src/test/java/tests/api/java/util/LinkedHashMapTest.java b/luni/src/test/java/tests/api/java/util/LinkedHashMapTest.java deleted file mode 100644 index eff9493..0000000 --- a/luni/src/test/java/tests/api/java/util/LinkedHashMapTest.java +++ /dev/null @@ -1,736 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -import tests.support.Support_MapTest2; -import tests.support.Support_UnmodifiableCollectionTest; - -/** - * java.util.LinkedHashMap - */ -public class LinkedHashMapTest extends junit.framework.TestCase { - - LinkedHashMap hm; - - final static int hmSize = 1000; - - Object[] objArray; - - Object[] objArray2; - - static final class CacheMap extends LinkedHashMap { - protected boolean removeEldestEntry(Map.Entry e) { - return size() > 5; - } - } - - private static class MockMapNull extends AbstractMap { - @Override - public Set entrySet() { - return null; - } - - @Override - public int size() { - return 10; - } - } - - /** - * java.util.LinkedHashMap#LinkedHashMap() - */ - public void test_Constructor() { - // Test for method java.util.LinkedHashMap() - new Support_MapTest2(new LinkedHashMap()).runTest(); - - LinkedHashMap hm2 = new LinkedHashMap(); - assertEquals("Created incorrect LinkedHashMap", 0, hm2.size()); - } - - /** - * java.util.LinkedHashMap#LinkedHashMap(int) - */ - public void test_ConstructorI() { - // Test for method java.util.LinkedHashMap(int) - LinkedHashMap hm2 = new LinkedHashMap(5); - assertEquals("Created incorrect LinkedHashMap", 0, hm2.size()); - try { - new LinkedHashMap(-1); - fail("Failed to throw IllegalArgumentException for initial " + - "capacity < 0"); - } catch (IllegalArgumentException e) { - //expected - } - - LinkedHashMap empty = new LinkedHashMap(0); - assertNull("Empty LinkedHashMap access", empty.get("nothing")); - empty.put("something", "here"); - assertTrue("cannot get element", empty.get("something") == "here"); - } - - /** - * java.util.LinkedHashMap#LinkedHashMap(int, float) - */ - public void test_ConstructorIF() { - // Test for method java.util.LinkedHashMap(int, float) - LinkedHashMap hm2 = new LinkedHashMap(5, (float) 0.5); - assertEquals("Created incorrect LinkedHashMap", 0, hm2.size()); - try { - new LinkedHashMap(0, 0); - fail("Failed to throw IllegalArgumentException for initial " + - "load factor <= 0"); - } catch (IllegalArgumentException e) { - //expected - } - - LinkedHashMap empty = new LinkedHashMap(0, 0.75f); - assertNull("Empty hashtable access", empty.get("nothing")); - empty.put("something", "here"); - assertTrue("cannot get element", empty.get("something") == "here"); - } - - /** - * java.util.LinkedHashMap#LinkedHashMap(java.util.Map) - */ - public void test_ConstructorLjava_util_Map() { - // Test for method java.util.LinkedHashMap(java.util.Map) - Map myMap = new TreeMap(); - for (int counter = 0; counter < hmSize; counter++) - myMap.put(objArray2[counter], objArray[counter]); - LinkedHashMap hm2 = new LinkedHashMap(myMap); - for (int counter = 0; counter < hmSize; counter++) - assertTrue("Failed to construct correct LinkedHashMap", hm - .get(objArray2[counter]) == hm2.get(objArray2[counter])); - } - - /** - * java.util.LinkedHashMap#get(java.lang.Object) - */ - public void test_getLjava_lang_Object() { - // Test for method java.lang.Object - // java.util.LinkedHashMap.get(java.lang.Object) - assertNull("Get returned non-null for non existent key", - hm.get("T")); - hm.put("T", "HELLO"); - assertEquals("Get returned incorecct value for existing key", "HELLO", hm.get("T") - ); - - LinkedHashMap m = new LinkedHashMap(); - m.put(null, "test"); - assertEquals("Failed with null key", "test", m.get(null)); - assertNull("Failed with missing key matching null hash", m - .get(new Integer(0))); - } - - /** - * java.util.LinkedHashMap#put(java.lang.Object, java.lang.Object) - */ - public void test_putLjava_lang_ObjectLjava_lang_Object() { - // Test for method java.lang.Object - // java.util.LinkedHashMap.put(java.lang.Object, java.lang.Object) - hm.put("KEY", "VALUE"); - assertEquals("Failed to install key/value pair", - "VALUE", hm.get("KEY")); - - LinkedHashMap m = new LinkedHashMap(); - m.put(new Short((short) 0), "short"); - m.put(null, "test"); - m.put(new Integer(0), "int"); - assertEquals("Failed adding to bucket containing null", "short", m.get( - new Short((short) 0))); - assertEquals("Failed adding to bucket containing null2", "int", m.get( - new Integer(0))); - } - - - public void test_putPresent() { - Map<String, String> m = new LinkedHashMap<String, String>(8, .75f, true); - m.put("KEY", "VALUE"); - m.put("WOMBAT", "COMBAT"); - m.put("KEY", "VALUE"); - Map.Entry newest = null; - for (Map.Entry<String, String> e : m.entrySet()) { - newest = e; - } - assertEquals("KEY", newest.getKey()); - assertEquals("VALUE", newest.getValue()); - } - - /** - * java.util.LinkedHashMap#putAll(java.util.Map) - */ - public void test_putAllLjava_util_Map() { - // Test for method void java.util.LinkedHashMap.putAll(java.util.Map) - LinkedHashMap hm2 = new LinkedHashMap(); - hm2.putAll(hm); - for (int i = 0; i < 1000; i++) - assertTrue("Failed to clear all elements", hm2.get( - new Integer(i).toString()).equals((new Integer(i)))); - } - - /** - * java.util.LinkedHashMap#putAll(java.util.Map) - */ - public void test_putAll_Ljava_util_Map_Null() { - LinkedHashMap linkedHashMap = new LinkedHashMap(); - try { - linkedHashMap.putAll(new MockMapNull()); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected. - } - - try { - linkedHashMap = new LinkedHashMap(new MockMapNull()); - fail("Should throw NullPointerException"); - } catch (NullPointerException e) { - // expected. - } - } - - /** - * java.util.LinkedHashMap#entrySet() - */ - public void test_entrySet() { - // Test for method java.util.Set java.util.LinkedHashMap.entrySet() - Set s = hm.entrySet(); - Iterator i = s.iterator(); - assertTrue("Returned set of incorrect size", hm.size() == s.size()); - while (i.hasNext()) { - Map.Entry m = (Map.Entry) i.next(); - assertTrue("Returned incorrect entry set", hm.containsKey(m - .getKey()) - && hm.containsValue(m.getValue())); - } - } - - public void test_entrySetRemove() { - entrySetRemoveHelper("military", "intelligence"); - entrySetRemoveHelper(null, "hypothesis"); - } - private void entrySetRemoveHelper(String key, String value) { - Map<String, String> m1 = new LinkedHashMap<String, String>(); - m1.put(key, value); - m1.put("jumbo", "shrimp"); - LinkedHashMap<String, String> m2 = new LinkedHashMap<String, String>(m1); - Set<Map.Entry<String, String>> s1 = m1.entrySet(); - s1.remove(m2.entrySet().iterator().next()); - assertEquals("jumbo", s1.iterator().next().getKey()); - } - - /** - * java.util.LinkedHashMap#keySet() - */ - public void test_keySet() { - // Test for method java.util.Set java.util.LinkedHashMap.keySet() - Set s = hm.keySet(); - assertTrue("Returned set of incorrect size()", s.size() == hm.size()); - for (int i = 0; i < objArray.length; i++) - assertTrue("Returned set does not contain all keys", s - .contains(objArray[i].toString())); - - LinkedHashMap m = new LinkedHashMap(); - m.put(null, "test"); - assertTrue("Failed with null key", m.keySet().contains(null)); - assertNull("Failed with null key", m.keySet().iterator().next()); - - Map map = new LinkedHashMap(101); - map.put(new Integer(1), "1"); - map.put(new Integer(102), "102"); - map.put(new Integer(203), "203"); - Iterator it = map.keySet().iterator(); - Integer remove1 = (Integer) it.next(); - it.hasNext(); - it.remove(); - Integer remove2 = (Integer) it.next(); - it.remove(); - ArrayList list = new ArrayList(Arrays.asList(new Integer[] { - new Integer(1), new Integer(102), new Integer(203) })); - list.remove(remove1); - list.remove(remove2); - assertTrue("Wrong result", it.next().equals(list.get(0))); - assertEquals("Wrong size", 1, map.size()); - assertTrue("Wrong contents", map.keySet().iterator().next().equals( - list.get(0))); - - Map map2 = new LinkedHashMap(101); - map2.put(new Integer(1), "1"); - map2.put(new Integer(4), "4"); - Iterator it2 = map2.keySet().iterator(); - Integer remove3 = (Integer) it2.next(); - Integer next; - if (remove3.intValue() == 1) - next = new Integer(4); - else - next = new Integer(1); - it2.hasNext(); - it2.remove(); - assertTrue("Wrong result 2", it2.next().equals(next)); - assertEquals("Wrong size 2", 1, map2.size()); - assertTrue("Wrong contents 2", map2.keySet().iterator().next().equals( - next)); - } - - /** - * java.util.LinkedHashMap#values() - */ - public void test_values() { - // Test for method java.util.Collection java.util.LinkedHashMap.values() - Collection c = hm.values(); - assertTrue("Returned collection of incorrect size()", c.size() == hm - .size()); - for (int i = 0; i < objArray.length; i++) - assertTrue("Returned collection does not contain all keys", c - .contains(objArray[i])); - - LinkedHashMap myLinkedHashMap = new LinkedHashMap(); - for (int i = 0; i < 100; i++) - myLinkedHashMap.put(objArray2[i], objArray[i]); - Collection values = myLinkedHashMap.values(); - new Support_UnmodifiableCollectionTest( - "Test Returned Collection From LinkedHashMap.values()", values) - .runTest(); - values.remove(new Integer(0)); - assertTrue( - "Removing from the values collection should remove from the original map", - !myLinkedHashMap.containsValue(new Integer(0))); - - } - - /** - * java.util.LinkedHashMap#remove(java.lang.Object) - */ - public void test_removeLjava_lang_Object() { - // Test for method java.lang.Object - // java.util.LinkedHashMap.remove(java.lang.Object) - int size = hm.size(); - Integer y = new Integer(9); - Integer x = ((Integer) hm.remove(y.toString())); - assertTrue("Remove returned incorrect value", x.equals(new Integer(9))); - assertNull("Failed to remove given key", hm.get(new Integer(9))); - assertTrue("Failed to decrement size", hm.size() == (size - 1)); - assertNull("Remove of non-existent key returned non-null", hm - .remove("LCLCLC")); - - LinkedHashMap m = new LinkedHashMap(); - m.put(null, "test"); - assertNull("Failed with same hash as null", - m.remove(new Integer(0))); - assertEquals("Failed with null key", "test", m.remove(null)); - } - - /** - * java.util.LinkedHashMap#clear() - */ - public void test_clear() { - // Test for method void java.util.LinkedHashMap.clear() - hm.clear(); - assertEquals("Clear failed to reset size", 0, hm.size()); - for (int i = 0; i < hmSize; i++) - assertNull("Failed to clear all elements", - hm.get(objArray2[i])); - - } - - /** - * java.util.LinkedHashMap#clone() - */ - public void test_clone() { - // Test for method java.lang.Object java.util.LinkedHashMap.clone() - LinkedHashMap hm2 = (LinkedHashMap) hm.clone(); - assertTrue("Clone answered equivalent LinkedHashMap", hm2 != hm); - for (int counter = 0; counter < hmSize; counter++) - assertTrue("Clone answered unequal LinkedHashMap", hm - .get(objArray2[counter]) == hm2.get(objArray2[counter])); - - LinkedHashMap map = new LinkedHashMap(); - map.put("key", "value"); - // get the keySet() and values() on the original Map - Set keys = map.keySet(); - Collection values = map.values(); - assertEquals("values() does not work", - "value", values.iterator().next()); - assertEquals("keySet() does not work", - "key", keys.iterator().next()); - AbstractMap map2 = (AbstractMap) map.clone(); - map2.put("key", "value2"); - Collection values2 = map2.values(); - assertTrue("values() is identical", values2 != values); - - // values() and keySet() on the cloned() map should be different - assertEquals("values() was not cloned", - "value2", values2.iterator().next()); - map2.clear(); - map2.put("key2", "value3"); - Set key2 = map2.keySet(); - assertTrue("keySet() is identical", key2 != keys); - assertEquals("keySet() was not cloned", - "key2", key2.iterator().next()); - } - - /** - * java.util.LinkedHashMap#clone() - */ - public void test_clone_ordered() { - // Test for method java.lang.Object java.util.LinkedHashMap.clone() - LinkedHashMap<String, String> hm1 = new LinkedHashMap<String, String>(10, 0.75f, true); - hm1.put("a", "a"); - hm1.put("b", "b"); - hm1.put("c", "c"); - LinkedHashMap<String, String> hm2 = (LinkedHashMap<String, String>) hm1.clone(); - hm1.get("a"); - - Map.Entry<String, String>[] set = new Map.Entry[3]; - Iterator<Map.Entry<String,String>> iterator = hm1.entrySet().iterator(); - - assertEquals("b", iterator.next().getKey()); - assertEquals("c", iterator.next().getKey()); - assertEquals("a", iterator.next().getKey()); - - iterator = hm2.entrySet().iterator(); - assertEquals("a", iterator.next().getKey()); - assertEquals("b", iterator.next().getKey()); - assertEquals("c", iterator.next().getKey()); - } - - // regresion test for HARMONY-4603 - public void test_clone_Mock() { - LinkedHashMap hashMap = new MockMap(); - String value = "value a"; - hashMap.put("key", value); - MockMap cloneMap = (MockMap) hashMap.clone(); - assertEquals(value, cloneMap.get("key")); - assertEquals(hashMap, cloneMap); - assertEquals(1, cloneMap.num); - - hashMap.put("key", "value b"); - assertFalse(hashMap.equals(cloneMap)); - } - - class MockMap extends LinkedHashMap { - int num; - - public Object put(Object k, Object v) { - num++; - return super.put(k, v); - } - - protected boolean removeEldestEntry(Map.Entry e) { - return num > 1; - } - } - - /** - * put/get interaction in access-order map where removeEldest - * returns true. - */ - public void test_removeEldestFromSameBucketAsNewEntry() { - LinkedHashMap<String, String> map - = new LinkedHashMap<String, String>(6, 0.75F, true) { - @Override - protected boolean removeEldestEntry(Entry<String, String> e) { - return true; - } - }; - map.put("N", "E"); - map.put("F", "I"); - assertEquals(null, map.get("N")); - } - - /** - * java.util.LinkedHashMap#containsKey(java.lang.Object) - */ - public void test_containsKeyLjava_lang_Object() { - // Test for method boolean - // java.util.LinkedHashMap.containsKey(java.lang.Object) - assertTrue("Returned false for valid key", hm.containsKey(new Integer( - 876).toString())); - assertTrue("Returned true for invalid key", !hm.containsKey("KKDKDKD")); - - LinkedHashMap m = new LinkedHashMap(); - m.put(null, "test"); - assertTrue("Failed with null key", m.containsKey(null)); - assertTrue("Failed with missing key matching null hash", !m - .containsKey(new Integer(0))); - } - - /** - * java.util.LinkedHashMap#containsValue(java.lang.Object) - */ - public void test_containsValueLjava_lang_Object() { - // Test for method boolean - // java.util.LinkedHashMap.containsValue(java.lang.Object) - assertTrue("Returned false for valid value", hm - .containsValue(new Integer(875))); - assertTrue("Returned true for invalid valie", !hm - .containsValue(new Integer(-9))); - } - - /** - * java.util.LinkedHashMap#isEmpty() - */ - public void test_isEmpty() { - // Test for method boolean java.util.LinkedHashMap.isEmpty() - assertTrue("Returned false for new map", new LinkedHashMap().isEmpty()); - assertTrue("Returned true for non-empty", !hm.isEmpty()); - } - - /** - * java.util.LinkedHashMap#size() - */ - public void test_size() { - // Test for method int java.util.LinkedHashMap.size() - assertTrue("Returned incorrect size", - hm.size() == (objArray.length + 2)); - } - - /** - * java.util.LinkedHashMap#entrySet() - */ - public void test_ordered_entrySet() { - int i; - int sz = 100; - LinkedHashMap lhm = new LinkedHashMap(); - for (i = 0; i < sz; i++) { - Integer ii = new Integer(i); - lhm.put(ii, ii.toString()); - } - - Set s1 = lhm.entrySet(); - Iterator it1 = s1.iterator(); - assertTrue("Returned set of incorrect size 1", lhm.size() == s1.size()); - for (i = 0; it1.hasNext(); i++) { - Map.Entry m = (Map.Entry) it1.next(); - Integer jj = (Integer) m.getKey(); - assertTrue("Returned incorrect entry set 1", jj.intValue() == i); - } - - LinkedHashMap lruhm = new LinkedHashMap(200, .75f, true); - for (i = 0; i < sz; i++) { - Integer ii = new Integer(i); - lruhm.put(ii, ii.toString()); - } - - Set s3 = lruhm.entrySet(); - Iterator it3 = s3.iterator(); - assertTrue("Returned set of incorrect size 2", lruhm.size() == s3 - .size()); - for (i = 0; i < sz && it3.hasNext(); i++) { - Map.Entry m = (Map.Entry) it3.next(); - Integer jj = (Integer) m.getKey(); - assertTrue("Returned incorrect entry set 2", jj.intValue() == i); - } - - /* fetch the even numbered entries to affect traversal order */ - int p = 0; - for (i = 0; i < sz; i += 2) { - String ii = (String) lruhm.get(new Integer(i)); - p = p + Integer.parseInt(ii); - } - assertEquals("invalid sum of even numbers", 2450, p); - - Set s2 = lruhm.entrySet(); - Iterator it2 = s2.iterator(); - assertTrue("Returned set of incorrect size 3", lruhm.size() == s2 - .size()); - for (i = 1; i < sz && it2.hasNext(); i += 2) { - Map.Entry m = (Map.Entry) it2.next(); - Integer jj = (Integer) m.getKey(); - assertTrue("Returned incorrect entry set 3", jj.intValue() == i); - } - for (i = 0; i < sz && it2.hasNext(); i += 2) { - Map.Entry m = (Map.Entry) it2.next(); - Integer jj = (Integer) m.getKey(); - assertTrue("Returned incorrect entry set 4", jj.intValue() == i); - } - assertTrue("Entries left to iterate on", !it2.hasNext()); - } - - /** - * java.util.LinkedHashMap#keySet() - */ - public void test_ordered_keySet() { - int i; - int sz = 100; - LinkedHashMap lhm = new LinkedHashMap(); - for (i = 0; i < sz; i++) { - Integer ii = new Integer(i); - lhm.put(ii, ii.toString()); - } - - Set s1 = lhm.keySet(); - Iterator it1 = s1.iterator(); - assertTrue("Returned set of incorrect size", lhm.size() == s1.size()); - for (i = 0; it1.hasNext(); i++) { - Integer jj = (Integer) it1.next(); - assertTrue("Returned incorrect entry set", jj.intValue() == i); - } - - LinkedHashMap lruhm = new LinkedHashMap(200, .75f, true); - for (i = 0; i < sz; i++) { - Integer ii = new Integer(i); - lruhm.put(ii, ii.toString()); - } - - Set s3 = lruhm.keySet(); - Iterator it3 = s3.iterator(); - assertTrue("Returned set of incorrect size", lruhm.size() == s3.size()); - for (i = 0; i < sz && it3.hasNext(); i++) { - Integer jj = (Integer) it3.next(); - assertTrue("Returned incorrect entry set", jj.intValue() == i); - } - - /* fetch the even numbered entries to affect traversal order */ - int p = 0; - for (i = 0; i < sz; i += 2) { - String ii = (String) lruhm.get(new Integer(i)); - p = p + Integer.parseInt(ii); - } - assertEquals("invalid sum of even numbers", 2450, p); - - Set s2 = lruhm.keySet(); - Iterator it2 = s2.iterator(); - assertTrue("Returned set of incorrect size", lruhm.size() == s2.size()); - for (i = 1; i < sz && it2.hasNext(); i += 2) { - Integer jj = (Integer) it2.next(); - assertTrue("Returned incorrect entry set", jj.intValue() == i); - } - for (i = 0; i < sz && it2.hasNext(); i += 2) { - Integer jj = (Integer) it2.next(); - assertTrue("Returned incorrect entry set", jj.intValue() == i); - } - assertTrue("Entries left to iterate on", !it2.hasNext()); - } - - /** - * java.util.LinkedHashMap#values() - */ - public void test_ordered_values() { - int i; - int sz = 100; - LinkedHashMap lhm = new LinkedHashMap(); - for (i = 0; i < sz; i++) { - Integer ii = new Integer(i); - lhm.put(ii, new Integer(i * 2)); - } - - Collection s1 = lhm.values(); - Iterator it1 = s1.iterator(); - assertTrue("Returned set of incorrect size 1", lhm.size() == s1.size()); - for (i = 0; it1.hasNext(); i++) { - Integer jj = (Integer) it1.next(); - assertTrue("Returned incorrect entry set 1", jj.intValue() == i * 2); - } - - LinkedHashMap lruhm = new LinkedHashMap(200, .75f, true); - for (i = 0; i < sz; i++) { - Integer ii = new Integer(i); - lruhm.put(ii, new Integer(i * 2)); - } - - Collection s3 = lruhm.values(); - Iterator it3 = s3.iterator(); - assertTrue("Returned set of incorrect size", lruhm.size() == s3.size()); - for (i = 0; i < sz && it3.hasNext(); i++) { - Integer jj = (Integer) it3.next(); - assertTrue("Returned incorrect entry set", jj.intValue() == i * 2); - } - - // fetch the even numbered entries to affect traversal order - int p = 0; - for (i = 0; i < sz; i += 2) { - Integer ii = (Integer) lruhm.get(new Integer(i)); - p = p + ii.intValue(); - } - assertTrue("invalid sum of even numbers", p == 2450 * 2); - - Collection s2 = lruhm.values(); - Iterator it2 = s2.iterator(); - assertTrue("Returned set of incorrect size", lruhm.size() == s2.size()); - for (i = 1; i < sz && it2.hasNext(); i += 2) { - Integer jj = (Integer) it2.next(); - assertTrue("Returned incorrect entry set", jj.intValue() == i * 2); - } - for (i = 0; i < sz && it2.hasNext(); i += 2) { - Integer jj = (Integer) it2.next(); - assertTrue("Returned incorrect entry set", jj.intValue() == i * 2); - } - assertTrue("Entries left to iterate on", !it2.hasNext()); - } - - /** - * java.util.LinkedHashMap#removeEldestEntry(java.util.Map$Entry) - */ - public void test_remove_eldest() { - int i; - int sz = 10; - CacheMap lhm = new CacheMap(); - for (i = 0; i < sz; i++) { - Integer ii = new Integer(i); - lhm.put(ii, new Integer(i * 2)); - } - - Collection s1 = lhm.values(); - Iterator it1 = s1.iterator(); - assertTrue("Returned set of incorrect size 1", lhm.size() == s1.size()); - for (i = 5; it1.hasNext(); i++) { - Integer jj = (Integer) it1.next(); - assertTrue("Returned incorrect entry set 1", jj.intValue() == i * 2); - } - assertTrue("Entries left in map", !it1.hasNext()); - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - objArray = new Object[hmSize]; - objArray2 = new Object[hmSize]; - for (int i = 0; i < objArray.length; i++) { - objArray[i] = new Integer(i); - objArray2[i] = objArray[i].toString(); - } - - hm = new LinkedHashMap(); - for (int i = 0; i < objArray.length; i++) - hm.put(objArray2[i], objArray[i]); - hm.put("test", null); - hm.put(null, "test"); - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - objArray = null; - objArray2 = null; - hm = null; - } -} diff --git a/luni/src/test/java/tests/api/java/util/LinkedHashSetTest.java b/luni/src/test/java/tests/api/java/util/LinkedHashSetTest.java deleted file mode 100644 index f54d01d..0000000 --- a/luni/src/test/java/tests/api/java/util/LinkedHashSetTest.java +++ /dev/null @@ -1,351 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.Vector; - -/** - * java.util.LinkedHashSet - */ - -public class LinkedHashSetTest extends junit.framework.TestCase { - - LinkedHashSet hs; - - Object[] objArray; - - /** - * java.util.LinkedHashSet#LinkedHashSet() - */ - public void test_Constructor() { - // Test for method java.util.LinkedHashSet() - LinkedHashSet hs2 = new LinkedHashSet(); - assertEquals("Created incorrect LinkedHashSet", 0, hs2.size()); - } - - /** - * java.util.LinkedHashSet#LinkedHashSet(int) - */ - public void test_ConstructorI() { - // Test for method java.util.LinkedHashSet(int) - LinkedHashSet hs2 = new LinkedHashSet(5); - assertEquals("Created incorrect LinkedHashSet", 0, hs2.size()); - try { - new LinkedHashSet(-1); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - } - - /** - * java.util.LinkedHashSet#LinkedHashSet(int, float) - */ - public void test_ConstructorIF() { - // Test for method java.util.LinkedHashSet(int, float) - LinkedHashSet hs2 = new LinkedHashSet(5, (float) 0.5); - assertEquals("Created incorrect LinkedHashSet", 0, hs2.size()); - - try { - new LinkedHashSet(-1, 0.5f); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - new LinkedHashSet(1, -0.5f); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - new LinkedHashSet(1, 0f); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - } - - /** - * java.util.LinkedHashSet#LinkedHashSet(java.util.Collection) - */ - public void test_ConstructorLjava_util_Collection() { - // Test for method java.util.LinkedHashSet(java.util.Collection) - LinkedHashSet hs2 = new LinkedHashSet(Arrays.asList(objArray)); - for (int counter = 0; counter < objArray.length; counter++) - assertTrue("LinkedHashSet does not contain correct elements", hs - .contains(objArray[counter])); - assertTrue("LinkedHashSet created from collection incorrect size", hs2 - .size() == objArray.length); - - try { - new LinkedHashSet(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.LinkedHashSet#add(java.lang.Object) - */ - public void test_addLjava_lang_Object() { - // Test for method boolean java.util.LinkedHashSet.add(java.lang.Object) - int size = hs.size(); - hs.add(new Integer(8)); - assertTrue("Added element already contained by set", hs.size() == size); - hs.add(new Integer(-9)); - assertTrue("Failed to increment set size after add", - hs.size() == size + 1); - assertTrue("Failed to add element to set", hs.contains(new Integer(-9))); - } - - /** - * java.util.LinkedHashSet#clear() - */ - public void test_clear() { - // Test for method void java.util.LinkedHashSet.clear() - Set orgSet = (Set) hs.clone(); - hs.clear(); - Iterator i = orgSet.iterator(); - assertEquals("Returned non-zero size after clear", 0, hs.size()); - while (i.hasNext()) - assertTrue("Failed to clear set", !hs.contains(i.next())); - } - - /** - * java.util.LinkedHashSet#clone() - */ - public void test_clone() { - // Test for method java.lang.Object java.util.LinkedHashSet.clone() - LinkedHashSet hs2 = (LinkedHashSet) hs.clone(); - assertTrue("clone returned an equivalent LinkedHashSet", hs != hs2); - assertTrue("clone did not return an equal LinkedHashSet", hs - .equals(hs2)); - } - - /** - * java.util.LinkedHashSet#contains(java.lang.Object) - */ - public void test_containsLjava_lang_Object() { - // Test for method boolean - // java.util.LinkedHashSet.contains(java.lang.Object) - assertTrue("Returned false for valid object", hs.contains(objArray[90])); - assertTrue("Returned true for invalid Object", !hs - .contains(new Object())); - - LinkedHashSet s = new LinkedHashSet(); - s.add(null); - assertTrue("Cannot handle null", s.contains(null)); - } - - /** - * java.util.LinkedHashSet#isEmpty() - */ - public void test_isEmpty() { - // Test for method boolean java.util.LinkedHashSet.isEmpty() - assertTrue("Empty set returned false", new LinkedHashSet().isEmpty()); - assertTrue("Non-empty set returned true", !hs.isEmpty()); - } - - /** - * java.util.LinkedHashSet#iterator() - */ - public void test_iterator() { - // Test for method java.util.Iterator java.util.LinkedHashSet.iterator() - Iterator i = hs.iterator(); - int x = 0; - int j; - for (j = 0; i.hasNext(); j++) { - Object oo = i.next(); - if (oo != null) { - Integer ii = (Integer) oo; - assertTrue("Incorrect element found", ii.intValue() == j); - } else { - assertTrue("Cannot find null", hs.contains(oo)); - } - ++x; - } - assertTrue("Returned iteration of incorrect size", hs.size() == x); - - LinkedHashSet s = new LinkedHashSet(); - s.add(null); - assertNull("Cannot handle null", s.iterator().next()); - } - - /** - * java.util.LinkedHashSet#remove(java.lang.Object) - */ - public void test_removeLjava_lang_Object() { - // Test for method boolean - // java.util.LinkedHashSet.remove(java.lang.Object) - int size = hs.size(); - hs.remove(new Integer(98)); - assertTrue("Failed to remove element", !hs.contains(new Integer(98))); - assertTrue("Failed to decrement set size", hs.size() == size - 1); - - LinkedHashSet s = new LinkedHashSet(); - s.add(null); - assertTrue("Cannot handle null", s.remove(null)); - } - - /** - * java.util.LinkedHashSet#size() - */ - public void test_size() { - // Test for method int java.util.LinkedHashSet.size() - assertTrue("Returned incorrect size", hs.size() == (objArray.length + 1)); - hs.clear(); - assertEquals("Cleared set returned non-zero size", 0, hs.size()); - } - - class Mock_LinkedHashSet extends LinkedHashSet { - @Override - public boolean retainAll(Collection c) { - throw new UnsupportedOperationException(); - } - } - - public void test_retainAllLjava_util_Collection() { - LinkedHashSet<Integer> lhs = new LinkedHashSet<Integer>(); - Vector v = new Vector<Float>(); - v.add(new Float(3.14)); - lhs.add(new Integer(1)); - assertEquals(1, lhs.size()); - lhs.retainAll(v); - assertEquals(0, lhs.size()); - v = new Vector<Integer>(); - v.add(new Integer(1)); - v.add(new Integer(2)); - v.add(new Integer(3)); - v.add(new Integer(4)); - v.add(new Integer(5)); - v.add(new Integer(6)); - lhs.add(new Integer(1)); - lhs.add(new Integer(6)); - lhs.add(new Integer(7)); - lhs.add(new Integer(8)); - lhs.add(new Integer(9)); - lhs.add(new Integer(10)); - lhs.add(new Integer(11)); - lhs.add(new Integer(12)); - lhs.add(new Integer(13)); - assertEquals(9, lhs.size()); - lhs.retainAll(v); - assertEquals(2, lhs.size()); - - try { - lhs.retainAll(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - - lhs = new Mock_LinkedHashSet(); - - try { - lhs.retainAll(v); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException e) { - //expected - } - } - - public void test_toArray() { - LinkedHashSet<Integer> lhs = new LinkedHashSet<Integer>(); - lhs.add(new Integer(1)); - lhs.add(new Integer(6)); - lhs.add(new Integer(7)); - lhs.add(new Integer(8)); - lhs.add(new Integer(9)); - lhs.add(new Integer(10)); - lhs.add(new Integer(11)); - lhs.add(new Integer(12)); - lhs.add(new Integer(13)); - - Object[] o = lhs.toArray(); - for (int i = 0; i < o.length; i++) { - assertTrue(lhs.contains(o[i])); - } - assertEquals(lhs.size(), o.length); - } - - public void test_toArray$Ljava_lang_Object() { - LinkedHashSet<Integer> lhs = new LinkedHashSet<Integer>(); - lhs.add(new Integer(1)); - lhs.add(new Integer(6)); - lhs.add(new Integer(7)); - lhs.add(new Integer(8)); - lhs.add(new Integer(9)); - lhs.add(new Integer(10)); - lhs.add(new Integer(11)); - lhs.add(new Integer(12)); - lhs.add(new Integer(13)); - - Object[] o1 = new Object[lhs.size()]; - Object[] o2 = new Double[lhs.size()]; - lhs.toArray(o1); - for (int i = 0; i < o1.length; i++) { - assertTrue(lhs.contains(o1[i])); - } - - try { - lhs.toArray(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - - try { - lhs.toArray(o2); - fail("ArrayStoreException expected"); - } catch (ArrayStoreException e) { - //expected - } - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - objArray = new Object[1000]; - for (int i = 0; i < objArray.length; i++) - objArray[i] = new Integer(i); - - hs = new LinkedHashSet(); - for (int i = 0; i < objArray.length; i++) - hs.add(objArray[i]); - hs.add(null); - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - objArray = null; - hs = null; - } -} diff --git a/luni/src/test/java/tests/api/java/util/LinkedListTest.java b/luni/src/test/java/tests/api/java/util/LinkedListTest.java deleted file mode 100644 index c0cec45..0000000 --- a/luni/src/test/java/tests/api/java/util/LinkedListTest.java +++ /dev/null @@ -1,658 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.ListIterator; -import java.util.NoSuchElementException; - - -import tests.support.Support_ListTest; - -public class LinkedListTest extends junit.framework.TestCase { - - LinkedList ll; - - Object[] objArray; - - /** - * java.util.LinkedList#LinkedList() - */ - public void test_Constructor() { - // Test for method java.util.LinkedList() - new Support_ListTest("", ll).runTest(); - - LinkedList subList = new LinkedList(); - for (int i = -50; i < 150; i++) - subList.add(new Integer(i)); - new Support_ListTest("", subList.subList(50, 150)).runTest(); - } - - /** - * java.util.LinkedList#LinkedList(java.util.Collection) - */ - public void test_ConstructorLjava_util_Collection() { - // Test for method java.util.LinkedList(java.util.Collection) - assertTrue("Incorrect LinkedList constructed", new LinkedList(ll) - .equals(ll)); - - try { - new LinkedList(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.LinkedList#add(int, java.lang.Object) - */ - public void test_addILjava_lang_Object() { - // Test for method void java.util.LinkedList.add(int, java.lang.Object) - Object o; - ll.add(50, o = "Test"); - assertTrue("Failed to add Object>: " + ll.get(50).toString(), ll - .get(50) == o); - assertTrue("Failed to fix up list after insert", - ll.get(51) == objArray[50] && (ll.get(52) == objArray[51])); - ll.add(50, null); - assertNull("Did not add null correctly", ll.get(50)); - } - - /** - * java.util.LinkedList#add(java.lang.Object) - */ - public void test_addLjava_lang_Object() { - // Test for method boolean java.util.LinkedList.add(java.lang.Object) - Object o; - ll.add(o = new Object()); - assertTrue("Failed to add Object", ll.getLast() == o); - ll.add(null); - assertNull("Did not add null correctly", ll.get(ll.size() - 1)); - } - - /** - * java.util.LinkedList#addAll(int, java.util.Collection) - */ - public void test_addAllILjava_util_Collection() { - // Test for method boolean java.util.LinkedList.addAll(int, - // java.util.Collection) - ll.addAll(50, (Collection) ll.clone()); - assertEquals("Returned incorrect size after adding to existing list", 200, ll - .size()); - for (int i = 0; i < 50; i++) - assertTrue("Manipulated elements < index", ll.get(i) == objArray[i]); - for (int i = 0; i >= 50 && (i < 150); i++) - assertTrue("Failed to ad elements properly", - ll.get(i) == objArray[i - 50]); - for (int i = 0; i >= 150 && (i < 200); i++) - assertTrue("Failed to ad elements properly", - ll.get(i) == objArray[i - 100]); - List myList = new LinkedList(); - myList.add(null); - myList.add("Blah"); - myList.add(null); - myList.add("Booga"); - myList.add(null); - ll.addAll(50, myList); - assertNull("a) List w/nulls not added correctly", ll.get(50)); - assertEquals("b) List w/nulls not added correctly", - "Blah", ll.get(51)); - assertNull("c) List w/nulls not added correctly", ll.get(52)); - assertEquals("d) List w/nulls not added correctly", - "Booga", ll.get(53)); - assertNull("e) List w/nulls not added correctly", ll.get(54)); - - try { - ll.addAll(-1, (Collection) null); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - //expected - } - - try { - ll.addAll(ll.size() + 1, (Collection) null); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - //expected - } - - try { - ll.addAll(0, null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.LinkedList#addAll(int, java.util.Collection) - */ - public void test_addAllILjava_util_Collection_2() { - // Regression for HARMONY-467 - LinkedList obj = new LinkedList(); - try { - obj.addAll(-1, (Collection) null); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - } - } - - /** - * java.util.LinkedList#addAll(java.util.Collection) - */ - public void test_addAllLjava_util_Collection() { - // Test for method boolean - // java.util.LinkedList.addAll(java.util.Collection) - List l = new ArrayList(); - l.addAll((Collection) ll.clone()); - for (int i = 0; i < ll.size(); i++) - assertTrue("Failed to add elements properly", l.get(i).equals( - ll.get(i))); - ll.addAll((Collection) ll.clone()); - assertEquals("Returned incorrect siZe after adding to existing list", 200, ll - .size()); - for (int i = 0; i < 100; i++) { - assertTrue("Added to list in incorrect order", ll.get(i).equals( - l.get(i))); - assertTrue("Failed to add to existing list", ll.get(i + 100) - .equals(l.get(i))); - } - List myList = new LinkedList(); - myList.add(null); - myList.add("Blah"); - myList.add(null); - myList.add("Booga"); - myList.add(null); - ll.addAll(myList); - assertNull("a) List w/nulls not added correctly", ll.get(200)); - assertEquals("b) List w/nulls not added correctly", - "Blah", ll.get(201)); - assertNull("c) List w/nulls not added correctly", ll.get(202)); - assertEquals("d) List w/nulls not added correctly", - "Booga", ll.get(203)); - assertNull("e) List w/nulls not added correctly", ll.get(204)); - - try { - ll.addAll(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.LinkedList#addFirst(java.lang.Object) - */ - public void test_addFirstLjava_lang_Object() { - // Test for method void java.util.LinkedList.addFirst(java.lang.Object) - Object o; - ll.addFirst(o = new Object()); - assertTrue("Failed to add Object", ll.getFirst() == o); - ll.addFirst(null); - assertNull("Failed to add null", ll.getFirst()); - } - - /** - * java.util.LinkedList#addLast(java.lang.Object) - */ - public void test_addLastLjava_lang_Object() { - // Test for method void java.util.LinkedList.addLast(java.lang.Object) - Object o; - ll.addLast(o = new Object()); - assertTrue("Failed to add Object", ll.getLast() == o); - ll.addLast(null); - assertNull("Failed to add null", ll.getLast()); - } - - /** - * java.util.LinkedList#clear() - */ - public void test_clear() { - // Test for method void java.util.LinkedList.clear() - ll.clear(); - for (int i = 0; i < ll.size(); i++) - assertNull("Failed to clear list", ll.get(i)); - } - - /** - * java.util.LinkedList#clone() - */ - public void test_clone() { - // Test for method java.lang.Object java.util.LinkedList.clone() - Object x = ll.clone(); - assertTrue("Cloned list was inequal to cloned", x.equals(ll)); - for (int i = 0; i < ll.size(); i++) - assertTrue("Cloned list contains incorrect elements", ll.get(i) - .equals(((LinkedList) x).get(i))); - ll.addFirst(null); - x = ll.clone(); - assertTrue("List with a null did not clone properly", ll.equals(x)); - } - - /** - * java.util.LinkedList#contains(java.lang.Object) - */ - public void test_containsLjava_lang_Object() { - // Test for method boolean - // java.util.LinkedList.contains(java.lang.Object) - assertTrue("Returned false for valid element", ll - .contains(objArray[99])); - assertTrue("Returned false for equal element", ll.contains(new Integer( - 8))); - assertTrue("Returned true for invalid element", !ll - .contains(new Object())); - assertTrue("Should not contain null", !ll.contains(null)); - ll.add(25, null); - assertTrue("Should contain null", ll.contains(null)); - } - - /** - * java.util.LinkedList#get(int) - */ - public void test_getI() { - // Test for method java.lang.Object java.util.LinkedList.get(int) - assertTrue("Returned incorrect element", ll.get(22) == objArray[22]); - try { - ll.get(8765); - fail("Failed to throw expected exception for index > size"); - } catch (IndexOutOfBoundsException e) { - } - } - - /** - * java.util.LinkedList#getFirst() - */ - public void test_getFirst() { - // Test for method java.lang.Object java.util.LinkedList.getFirst() - assertTrue("Returned incorrect first element", ll.getFirst().equals( - objArray[0])); - - ll.clear(); - try { - ll.getFirst(); - fail("NoSuchElementException expected"); - } catch (NoSuchElementException e) { - //expected - } - } - - /** - * java.util.LinkedList#getLast() - */ - public void test_getLast() { - // Test for method java.lang.Object java.util.LinkedList.getLast() - assertTrue("Returned incorrect first element", ll.getLast().equals( - objArray[objArray.length - 1])); - - ll.clear(); - try { - ll.getLast(); - fail("NoSuchElementException expected"); - } catch (NoSuchElementException e) { - //expected - } - } - - /** - * java.util.LinkedList#indexOf(java.lang.Object) - */ - public void test_indexOfLjava_lang_Object() { - // Test for method int java.util.LinkedList.indexOf(java.lang.Object) - assertEquals("Returned incorrect index", 87, ll.indexOf(objArray[87])); - assertEquals("Returned index for invalid Object", -1, ll - .indexOf(new Object())); - ll.add(20, null); - ll.add(24, null); - assertTrue("Index of null should be 20, but got: " + ll.indexOf(null), - ll.indexOf(null) == 20); - } - - /** - * java.util.LinkedList#lastIndexOf(java.lang.Object) - */ - public void test_lastIndexOfLjava_lang_Object() { - // Test for method int - // java.util.LinkedList.lastIndexOf(java.lang.Object) - ll.add(new Integer(99)); - assertEquals("Returned incorrect index", - 100, ll.lastIndexOf(objArray[99])); - assertEquals("Returned index for invalid Object", -1, ll - .lastIndexOf(new Object())); - ll.add(20, null); - ll.add(24, null); - assertTrue("Last index of null should be 20, but got: " - + ll.lastIndexOf(null), ll.lastIndexOf(null) == 24); - } - - /** - * java.util.LinkedList#listIterator(int) - */ - public void test_listIteratorI() { - // Test for method java.util.ListIterator - // java.util.LinkedList.listIterator(int) - ListIterator i1 = ll.listIterator(); - ListIterator i2 = ll.listIterator(0); - Object elm; - int n = 0; - while (i2.hasNext()) { - if (n == 0 || n == objArray.length - 1) { - if (n == 0) - assertTrue("First element claimed to have a previous", !i2 - .hasPrevious()); - if (n == objArray.length) - assertTrue("Last element claimed to have next", !i2 - .hasNext()); - } - elm = i2.next(); - assertTrue("Iterator returned elements in wrong order", - elm == objArray[n]); - if (n > 0 && n < objArray.length - 1) { - assertTrue("Next index returned incorrect value", - i2.nextIndex() == n + 1); - assertTrue("previousIndex returned incorrect value : " - + i2.previousIndex() + ", n val: " + n, i2 - .previousIndex() == n); - } - elm = i1.next(); - assertTrue("Iterator returned elements in wrong order", - elm == objArray[n]); - ++n; - } - - i2 = ll.listIterator(ll.size()/2); - assertTrue((Integer)i2.next() == ll.size()/2); - List myList = new LinkedList(); - myList.add(null); - myList.add("Blah"); - myList.add(null); - myList.add("Booga"); - myList.add(null); - ListIterator li = myList.listIterator(); - assertTrue("li.hasPrevious() should be false", !li.hasPrevious()); - assertNull("li.next() should be null", li.next()); - assertTrue("li.hasPrevious() should be true", li.hasPrevious()); - assertNull("li.prev() should be null", li.previous()); - assertNull("li.next() should be null", li.next()); - assertEquals("li.next() should be Blah", "Blah", li.next()); - assertNull("li.next() should be null", li.next()); - assertEquals("li.next() should be Booga", "Booga", li.next()); - assertTrue("li.hasNext() should be true", li.hasNext()); - assertNull("li.next() should be null", li.next()); - assertTrue("li.hasNext() should be false", !li.hasNext()); - - try { - ll.listIterator(-1); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - //expected - } - - try { - ll.listIterator(ll.size() + 1); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - //expected - } - } - - /** - * java.util.LinkedList#remove(int) - */ - public void test_removeI() { - // Test for method java.lang.Object java.util.LinkedList.remove(int) - ll.remove(10); - assertEquals("Failed to remove element", -1, ll.indexOf(objArray[10])); - try { - ll.remove(999); - fail("Failed to throw expected exception when index out of range"); - } catch (IndexOutOfBoundsException e) { - // Correct - } - - ll.add(20, null); - ll.remove(20); - assertNotNull("Should have removed null", ll.get(20)); - } - - /** - * java.util.LinkedList#remove(java.lang.Object) - */ - public void test_removeLjava_lang_Object() { - // Test for method boolean java.util.LinkedList.remove(java.lang.Object) - assertTrue("Failed to remove valid Object", ll.remove(objArray[87])); - assertTrue("Removed invalid object", !ll.remove(new Object())); - assertEquals("Found Object after removal", -1, ll.indexOf(objArray[87])); - ll.add(null); - ll.remove(null); - assertTrue("Should not contain null afrer removal", !ll.contains(null)); - } - - /** - * java.util.LinkedList#removeFirst() - */ - public void test_removeFirst() { - // Test for method java.lang.Object java.util.LinkedList.removeFirst() - ll.removeFirst(); - assertTrue("Failed to remove first element", - ll.getFirst() != objArray[0]); - - ll.clear(); - try { - ll.removeFirst(); - fail("NoSuchElementException expected"); - } catch (NoSuchElementException e) { - //expected - } - } - - /** - * java.util.LinkedList#removeLast() - */ - public void test_removeLast() { - // Test for method java.lang.Object java.util.LinkedList.removeLast() - ll.removeLast(); - assertTrue("Failed to remove last element", - ll.getLast() != objArray[objArray.length - 1]); - - ll.clear(); - try { - ll.removeLast(); - fail("NoSuchElementException expected"); - } catch (NoSuchElementException e) { - //expected - } - } - - /** - * java.util.LinkedList#set(int, java.lang.Object) - */ - public void test_setILjava_lang_Object() { - // Test for method java.lang.Object java.util.LinkedList.set(int, - // java.lang.Object) - Object obj; - ll.set(65, obj = new Object()); - assertTrue("Failed to set object", ll.get(65) == obj); - - try { - ll.set(-1, obj = new Object()); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - //expected - } - - try { - ll.set(ll.size() + 1, obj = new Object()); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - //expected - } - } - - /** - * java.util.LinkedList#size() - */ - public void test_size() { - // Test for method int java.util.LinkedList.size() - assertTrue("Returned incorrect size", ll.size() == objArray.length); - ll.removeFirst(); - assertTrue("Returned incorrect size", ll.size() == objArray.length - 1); - } - - /** - * java.util.LinkedList#toArray() - */ - public void test_toArray() { - // Test for method java.lang.Object [] java.util.LinkedList.toArray() - ll.add(null); - Object[] obj = ll.toArray(); - assertEquals("Returned array of incorrect size", objArray.length + 1, obj.length); - - for (int i = 0; i < obj.length - 1; i++) - assertTrue("Returned incorrect array: " + i, obj[i] == objArray[i]); - assertNull("Returned incorrect array--end isn't null", - obj[obj.length - 1]); - } - - /** - * java.util.LinkedList#toArray(java.lang.Object[]) - */ - public void test_toArray$Ljava_lang_Object() { - // Test for method java.lang.Object [] - // java.util.LinkedList.toArray(java.lang.Object []) - Integer[] argArray = new Integer[100]; - Object[] retArray; - retArray = ll.toArray(argArray); - assertTrue("Returned different array than passed", retArray == argArray); - List retList = new LinkedList(Arrays.asList(retArray)); - Iterator li = ll.iterator(); - Iterator ri = retList.iterator(); - while (li.hasNext()) - assertTrue("Lists are not equal", li.next() == ri.next()); - argArray = new Integer[1000]; - retArray = ll.toArray(argArray); - assertNull("Failed to set first extra element to null", argArray[ll - .size()]); - for (int i = 0; i < ll.size(); i++) - assertTrue("Returned incorrect array: " + i, - retArray[i] == objArray[i]); - ll.add(50, null); - argArray = new Integer[101]; - retArray = ll.toArray(argArray); - assertTrue("Returned different array than passed", retArray == argArray); - retArray = ll.toArray(argArray); - assertTrue("Returned different array than passed", retArray == argArray); - retList = new LinkedList(Arrays.asList(retArray)); - li = ll.iterator(); - ri = retList.iterator(); - while (li.hasNext()) - assertTrue("Lists are not equal", li.next() == ri.next()); - - try { - ll.toArray(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - - LinkedList<String> lls = new LinkedList<String>(); - lls.add("First"); - lls.add("Second"); - - try { - lls.toArray(argArray); - fail("ArrayStoreException expected"); - } catch (ArrayStoreException e) { - //expected - } - } - public void test_offer() { - int origSize = ll.size(); - assertTrue("offer() should return true'", ll.offer(objArray[0])); - assertEquals("offer() should add an element as the last one", origSize, ll.lastIndexOf(objArray[0])); - } - public void test_poll() { - for (int i = 0; i < objArray.length; i++) { - assertEquals("should remove the head", objArray[i], ll.poll()); - } - assertEquals("should be empty", 0, ll.size()); - assertNull("should return 'null' if list is empty", ll.poll()); - } - public void test_remove() { - for (int i = 0; i < objArray.length; i++) { - assertEquals("should remove the head", objArray[i], ll.remove()); - } - assertEquals("should be empty", 0, ll.size()); - try { - ll.remove(); - fail("NoSuchElementException is expected when removing from the empty list"); - } catch (NoSuchElementException e) { - //-- expected - } - } - public void test_element() { - assertEquals("should return the head", objArray[0], ll.element()); - assertEquals("element() should remove nothing", objArray.length, ll.size()); - try { - new LinkedList().remove(); - fail("NoSuchElementException is expected when the list is empty"); - } catch (NoSuchElementException e) { - //-- expected - } - } - - public void test_peek() { - assertEquals("should remove the head", objArray[0], ll.peek()); - assertEquals("should remove the head", objArray[0], ll.peek()); - - ll.clear(); - - assertNull("should return 'null' if list is empty", ll.peek()); - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() throws Exception { - super.setUp(); - - objArray = new Object[100]; - for (int i = 0; i < objArray.length; i++) { - objArray[i] = new Integer(i); - } - - ll = new LinkedList(); - for (int i = 0; i < objArray.length; i++) { - ll.add(objArray[i]); - } - } - - @Override - protected void tearDown() throws Exception { - objArray = null; - ll = null; - - super.tearDown(); - } -} diff --git a/luni/src/test/java/tests/api/java/util/ListResourceBundleTest.java b/luni/src/test/java/tests/api/java/util/ListResourceBundleTest.java deleted file mode 100644 index 8be04db..0000000 --- a/luni/src/test/java/tests/api/java/util/ListResourceBundleTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.Enumeration; -import java.util.ListResourceBundle; -import java.util.Locale; -import java.util.ResourceBundle; -import java.util.Vector; - -public class ListResourceBundleTest extends junit.framework.TestCase { - - /** - * java.util.ListResourceBundle#getKeys() - */ - public void test_getKeys() { - ResourceBundle bundle; - String name = "tests.support.Support_TestResource"; - Locale.setDefault(new Locale("en", "US")); - bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR")); - Enumeration keys = bundle.getKeys(); - Vector result = new Vector(); - while (keys.hasMoreElements()) { - result.addElement(keys.nextElement()); - } - assertTrue("Missing key parent1", result.contains("parent1")); - assertTrue("Missing key parent2", result.contains("parent2")); - assertTrue("Missing key parent3", result.contains("parent3")); - assertTrue("Missing key parent4", result.contains("parent4")); - assertTrue("Missing key child1", result.contains("child1")); - assertTrue("Missing key child2", result.contains("child2")); - assertTrue("Missing key child3", result.contains("child3")); - } - - - public void test_handleGetObjectLjava_lang_String() { - ListResourceBundle bundle; - String name = "tests.support.Support_TestResource"; - Locale.setDefault(new Locale("en", "US")); - bundle = (ListResourceBundle)ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR")); - Enumeration keys = bundle.getKeys(); - String keyValue = null; - Vector result = new Vector(); - while (keys.hasMoreElements()) { - result.addElement(bundle.handleGetObject((String)keys.nextElement())); - } - assertEquals(9, result.size()); - assertTrue(result.contains(null)); - assertTrue(result.contains("frFRVARValue4")); - assertTrue(result.contains("frFRVARChildValue1")); - assertTrue(result.contains("frFRVARChildValue2")); - assertTrue(result.contains("frFRVARChildValue3")); - assertTrue(result.remove(null)); - assertTrue(result.remove(null)); - assertTrue(result.remove(null)); - } - - protected void setUp() { - } - - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/util/LocaleTest.java b/luni/src/test/java/tests/api/java/util/LocaleTest.java deleted file mode 100644 index 7615a76..0000000 --- a/luni/src/test/java/tests/api/java/util/LocaleTest.java +++ /dev/null @@ -1,416 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.security.Permission; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.Set; - -public class LocaleTest extends junit.framework.TestCase { - - Locale testLocale; - - Locale l; - - Locale defaultLocale; - - /** - * java.util.Locale#Locale(java.lang.String, java.lang.String) - */ - public void test_ConstructorLjava_lang_String() { - // Test for method java.util.Locale(java.lang.String) - Locale x = new Locale("xx"); - assertTrue("Failed to create Locale", x.getVariant().equals("")); - - try { - new Locale(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.Locale#Locale(java.lang.String, java.lang.String) - */ - public void test_ConstructorLjava_lang_StringLjava_lang_String() { - // Test for method java.util.Locale(java.lang.String, java.lang.String) - Locale x = new Locale("xx", "CV"); - assertTrue("Failed to create Locale", x.getCountry().equals("CV") - && x.getVariant().equals("")); - - try { - new Locale("xx", null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - - try { - new Locale(null, "CV"); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.Locale#Locale(java.lang.String, java.lang.String, - * java.lang.String) - */ - public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_String() { - // Test for method java.util.Locale(java.lang.String, java.lang.String, - // java.lang.String) - Locale x = new Locale("xx", "CV", "ZZ"); - assertTrue("Failed to create Locale", x.getLanguage().equals("xx") - && (x.getCountry().equals("CV") && x.getVariant().equals("ZZ"))); - try { - new Locale(null, "CV", "ZZ"); - fail("expected NullPointerException with 1st parameter == null"); - } catch(NullPointerException e) { - } - - try { - new Locale("xx", null, "ZZ"); - fail("expected NullPointerException with 2nd parameter == null"); - } catch(NullPointerException e) { - } - - try { - new Locale("xx", "CV", null); - fail("expected NullPointerException with 3rd parameter == null"); - } catch(NullPointerException e) { - } - } - - /** - * java.util.Locale#clone() - */ - public void test_clone() { - // Test for method java.lang.Object java.util.Locale.clone() - assertTrue("Clone failed", l.clone().equals(l)); - } - - /** - * java.util.Locale#equals(java.lang.Object) - */ - public void test_equalsLjava_lang_Object() { - // Test for method boolean java.util.Locale.equals(java.lang.Object) - Locale l2 = new Locale("en", "CA", "WIN32"); - assertTrue("Same object returned false", testLocale.equals(testLocale)); - assertTrue("Same values returned false", testLocale.equals(l2)); - assertTrue("Different locales returned true", !testLocale.equals(l)); - - } - - /** - * java.util.Locale#getAvailableLocales() - */ - public void test_getAvailableLocales() { -// BEGIN android-changed - // Test for method java.util.Locale [] - // java.util.Locale.getAvailableLocales() - // Assumes there will generally be about 10+ available locales... - // even in minimal configurations for android - try { - Locale[] locales = Locale.getAvailableLocales(); - assertTrue("Wrong number of locales: " + locales.length, locales.length > 10); - // regression test for HARMONY-1514 - // HashSet can filter duplicate locales - Set<Locale> localesSet = new HashSet<Locale>(Arrays.asList(locales)); - assertEquals(localesSet.size(), locales.length); - } catch (Exception e) { - fail("Exception during test : " + e.getMessage()); - } -// END android-changed - } - - /** - * java.util.Locale#getCountry() - */ - public void test_getCountry() { - // Test for method java.lang.String java.util.Locale.getCountry() - assertTrue("Returned incorrect country: " + testLocale.getCountry(), - testLocale.getCountry().equals("CA")); - } - - /** - * java.util.Locale#getDefault() - */ - public void test_getDefault() { - // Test for method java.util.Locale java.util.Locale.getDefault() - assertTrue("returns copy", Locale.getDefault() == Locale.getDefault()); - Locale org = Locale.getDefault(); - Locale.setDefault(l); - Locale x = Locale.getDefault(); - Locale.setDefault(org); - assertEquals("Failed to get locale", "fr_CA_WIN32", x.toString()); - } - - /** - * java.util.Locale#getDisplayCountry() - */ - public void test_getDisplayCountry() { - // Test for method java.lang.String java.util.Locale.getDisplayCountry() - assertTrue("Returned incorrect country: " - + testLocale.getDisplayCountry(), testLocale - .getDisplayCountry().equals("Canada")); - - // Regression for Harmony-1146 - Locale l_countryCD = new Locale("", "CD"); - assertEquals("Congo [DRC]", - l_countryCD.getDisplayCountry()); - } - - public void test_getDisplayCountryLjava_util_Locale() { - assertEquals("Italie", Locale.ITALY.getDisplayCountry(new Locale("fr", "CA", "WIN32"))); - } - - /** - * java.util.Locale#getDisplayLanguage() - */ - public void test_getDisplayLanguage() { - // Test for method java.lang.String - // java.util.Locale.getDisplayLanguage() - assertTrue("Returned incorrect language: " - + testLocale.getDisplayLanguage(), testLocale - .getDisplayLanguage().equals("English")); - - // Regression for Harmony-1146 - Locale l_languageAE = new Locale("ae", ""); - assertEquals("Avestan", l_languageAE.getDisplayLanguage()); - } - - public void test_getDisplayLanguageLjava_util_Locale() { - assertEquals("anglais", new Locale("en", "CA", "WIN32").getDisplayLanguage(l)); - } - - public void test_getDisplayName() { - assertEquals("English (Canada,WIN32)", new Locale("en", "CA", "WIN32").getDisplayName()); - } - - public void test_getDisplayNameLjava_util_Locale() { - assertEquals("anglais (Canada,WIN32)", new Locale("en", "CA", "WIN32").getDisplayName(l)); - } - - /** - * java.util.Locale#getDisplayVariant() - */ - public void test_getDisplayVariant() { - // Test for method java.lang.String java.util.Locale.getDisplayVariant() - assertTrue("Returned incorrect variant: " - + testLocale.getDisplayVariant(), testLocale - .getDisplayVariant().equals("WIN32")); - } - - /** - * java.util.Locale#getDisplayVariant(java.util.Locale) - */ - public void test_getDisplayVariantLjava_util_Locale() { - // Test for method java.lang.String - // java.util.Locale.getDisplayVariant(java.util.Locale) - assertTrue("Returned incorrect variant: " - + testLocale.getDisplayVariant(l), testLocale - .getDisplayVariant(l).equals("WIN32")); - } - - public void test_getISO3Language() { - Locale l = new Locale("ae"); - assertEquals("ave", l.getISO3Language()); - - // Regression for Harmony-1146 - Locale l_CountryCS = new Locale("", "CS"); - assertEquals("SCG", l_CountryCS.getISO3Country()); - - // Regression for Harmony-1129 - l = new Locale("ak", ""); - assertEquals("aka", l.getISO3Language()); - } - - /** - * java.util.Locale#getISOCountries() - */ - public void test_getISOCountries() { - // Test for method java.lang.String [] - // java.util.Locale.getISOCountries() - // Assumes all countries are 2 digits, and that there will always be - // 230 countries on the list... - String[] isoCountries = Locale.getISOCountries(); - int length = isoCountries.length; - int familiarCount = 0; - for (int i = 0; i < length; i++) { - if (isoCountries[i].length() != 2) { - fail("Wrong format for ISOCountries."); - } - if (isoCountries[i].equals("CA") || isoCountries[i].equals("BB") - || isoCountries[i].equals("US") - || isoCountries[i].equals("KR")) - familiarCount++; - } - assertTrue("ISOCountries missing.", familiarCount == 4 && length > 230); - } - - /** - * java.util.Locale#getISOLanguages() - */ - public void test_getISOLanguages() { - // Test for method java.lang.String [] - // java.util.Locale.getISOLanguages() - // Assumes always at least 131 ISOlanguages... - String[] isoLang = Locale.getISOLanguages(); - int length = isoLang.length; - - // BEGIN android-changed - // Language codes are 2- and 3-letter, with preference given - // to 2-letter codes where possible. 3-letter codes are used - // when lack a 2-letter equivalent. - assertTrue("Random element in wrong format.", - (isoLang[length / 2].length() == 2 || isoLang[length / 2].length() == 3) - && isoLang[length / 2].toLowerCase().equals(isoLang[length / 2])); - // END android-changed - - assertTrue("Wrong number of ISOLanguages.", length > 130); - } - - /** - * java.util.Locale#getLanguage() - */ - public void test_getLanguage() { - // Test for method java.lang.String java.util.Locale.getLanguage() - assertTrue("Returned incorrect language: " + testLocale.getLanguage(), - testLocale.getLanguage().equals("en")); - } - - /** - * java.util.Locale#getVariant() - */ - public void test_getVariant() { - // Test for method java.lang.String java.util.Locale.getVariant() - assertTrue("Returned incorrect variant: " + testLocale.getVariant(), - testLocale.getVariant().equals("WIN32")); - } - - SecurityManager sm = new SecurityManager() { - final String forbidenPermissionName = "user.language"; - - public void checkPermission(Permission perm) { - if (perm.getName().equals(forbidenPermissionName)) { - throw new SecurityException(); - } - } - }; - /** - * java.util.Locale#setDefault(java.util.Locale) - */ - public void test_setDefaultLjava_util_Locale() { - // Test for method void java.util.Locale.setDefault(java.util.Locale) - - Locale org = Locale.getDefault(); - Locale.setDefault(l); - Locale x = Locale.getDefault(); - Locale.setDefault(org); - assertEquals("Failed to set locale", "fr_CA_WIN32", x.toString()); - - Locale.setDefault(new Locale("tr", "")); - String res1 = "\u0069".toUpperCase(); - String res2 = "\u0049".toLowerCase(); - Locale.setDefault(org); - assertEquals("Wrong toUppercase conversion", "\u0130", res1); - assertEquals("Wrong toLowercase conversion", "\u0131", res2); - - try { - Locale.setDefault(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.Locale#toString() - */ - public void test_toString() { - // Test for method java.lang.String java.util.Locale.toString() - assertEquals("en_CA_WIN32", new Locale("en", "CA", "WIN32").toString()); - - Locale l = new Locale("en", ""); - assertEquals("Wrong representation 1", "en", l.toString()); - l = new Locale("", "CA"); - assertEquals("Wrong representation 2", "_CA", l.toString()); - l = new Locale("", "CA", "var"); - assertEquals("Wrong representation 2.5", "_CA_var", l.toString()); - l = new Locale("en", "", "WIN"); - assertEquals("Wrong representation 4", "en__WIN", l.toString()); - l = new Locale("en", "CA"); - assertEquals("Wrong representation 6", "en_CA", l.toString()); - l = new Locale("en", "CA", "VAR"); - assertEquals("Wrong representation 7", "en_CA_VAR", l.toString()); - - l = new Locale("", "", "var"); - assertEquals("Wrong representation 8", "", l.toString()); - - } - - public void test_hashCode() { - Locale l1 = new Locale("en", "US"); - Locale l2 = new Locale("fr", "CA"); - - assertTrue(l1.hashCode() != l2.hashCode()); - } - -// BEGIN android-removed -// These locales are not part of the android reference impl -// // Regression Test for HARMONY-2953 -// public void test_getISO() { -// Locale locale = new Locale("an"); -// assertEquals("arg", locale.getISO3Language()); -// -// locale = new Locale("PS"); -// assertEquals("pus", locale.getISO3Language()); -// -// List<String> languages = Arrays.asList(Locale.getISOLanguages()); -// assertTrue(languages.contains("ak")); -// -// List<String> countries = Arrays.asList(Locale.getISOCountries()); -// assertTrue(countries.contains("CS")); -// } -// END android-removed - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - defaultLocale = Locale.getDefault(); - Locale.setDefault(Locale.US); - testLocale = new Locale("en", "CA", "WIN32"); - l = new Locale("fr", "CA", "WIN32"); - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - Locale.setDefault(defaultLocale); - } -} diff --git a/luni/src/test/java/tests/api/java/util/MissingResourceExceptionTest.java b/luni/src/test/java/tests/api/java/util/MissingResourceExceptionTest.java deleted file mode 100644 index fc7189e..0000000 --- a/luni/src/test/java/tests/api/java/util/MissingResourceExceptionTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -public class MissingResourceExceptionTest extends junit.framework.TestCase { - - /** - * java.util.MissingResourceException#MissingResourceException(java.lang.String, - * java.lang.String, java.lang.String) - */ - public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_String() { - // Test for method java.util.MissingResourceException(java.lang.String, - // java.lang.String, java.lang.String) - assertNotNull(new MissingResourceException("Detail string", "Class name string", "Key string")); - assertNotNull(new MissingResourceException(null, "Class name string", "Key string")); - assertNotNull(new MissingResourceException("Detail string", null, "Key string")); - assertNotNull(new MissingResourceException("Detail string", "Class name string", null)); - try { - ResourceBundle.getBundle("Non-ExistentBundle"); - } catch (MissingResourceException e) { - return; - } - fail("Failed to generate expected exception"); - } - - /** - * java.util.MissingResourceException#getClassName() - */ - public void test_getClassName() { - // Test for method java.lang.String - // java.util.MissingResourceException.getClassName() - try { - ResourceBundle.getBundle("Non-ExistentBundle"); - } catch (MissingResourceException e) { - assertEquals("Returned incorrect class name", "Non-ExistentBundle" - + '_' + Locale.getDefault(), e.getClassName()); - } - } - - /** - * java.util.MissingResourceException#getKey() - */ - public void test_getKey() { - // Test for method java.lang.String - // java.util.MissingResourceException.getKey() - try { - ResourceBundle.getBundle("Non-ExistentBundle"); - } catch (MissingResourceException e) { - assertTrue("Returned incorrect class name", e.getKey().equals("")); - } - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/util/NoSuchElementExceptionTest.java b/luni/src/test/java/tests/api/java/util/NoSuchElementExceptionTest.java deleted file mode 100644 index cfda941..0000000 --- a/luni/src/test/java/tests/api/java/util/NoSuchElementExceptionTest.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.NoSuchElementException; -import java.util.Vector; - -public class NoSuchElementExceptionTest extends junit.framework.TestCase { - - /** - * java.util.NoSuchElementException#NoSuchElementException() - */ - public void test_Constructor() { - // Test for method java.util.NoSuchElementException() - - assertNotNull(new NoSuchElementException()); - - try { - Vector v = new Vector(); - v.elements().nextElement(); - fail("NoSuchElementException expected"); - } catch (NoSuchElementException e) { - //expected - } - } - - /** - * java.util.NoSuchElementException#NoSuchElementException(java.lang.String) - */ - public void test_ConstructorLjava_lang_String() { - // Test for method java.util.NoSuchElementException(java.lang.String) - - assertNotNull(new NoSuchElementException("String")); - assertNotNull(new NoSuchElementException(null)); - - try { - Vector v = new Vector(); - v.firstElement(); - fail("NoSuchElementException expected"); - } catch (NoSuchElementException e) { - //expected - } - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/util/ObservableTest.java b/luni/src/test/java/tests/api/java/util/ObservableTest.java deleted file mode 100644 index 3a0d31c..0000000 --- a/luni/src/test/java/tests/api/java/util/ObservableTest.java +++ /dev/null @@ -1,246 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.Observable; -import java.util.Observer; -import java.util.Vector; - -public class ObservableTest extends junit.framework.TestCase { - - static class TestObserver implements Observer { - public Vector objv = new Vector(); - - int updateCount = 0; - - public void update(Observable observed, Object arg) { - ++updateCount; - objv.add(arg); - } - - public int updateCount() { - return updateCount; - } - - } - - static class DeleteTestObserver implements Observer { - int updateCount = 0; - - boolean deleteAll = false; - - public DeleteTestObserver(boolean all) { - deleteAll = all; - } - - public void update(Observable observed, Object arg) { - ++updateCount; - if (deleteAll) - observed.deleteObservers(); - else - observed.deleteObserver(this); - } - - public int updateCount() { - return updateCount; - } - - } - - static class TestObservable extends Observable { - public void doChange() { - setChanged(); - } - - public void clearChange() { - clearChanged(); - } - } - - Observer observer; - - TestObservable observable; - - /** - * java.util.Observable#Observable() - */ - public void test_Constructor() { - // Test for method java.util.Observable() - try { - Observable ov = new Observable(); - assertTrue("Wrong initial values.", !ov.hasChanged()); - assertEquals("Wrong initial values.", 0, ov.countObservers()); - } catch (Exception e) { - fail("Exception during test : " + e.getMessage()); - } - } - - /** - * java.util.Observable#addObserver(java.util.Observer) - */ - public void test_addObserverLjava_util_Observer() { - // Test for method void - // java.util.Observable.addObserver(java.util.Observer) - TestObserver test = new TestObserver(); - observable.addObserver(test); - assertEquals("Failed to add observer", 1, observable.countObservers()); - observable.addObserver(test); - assertEquals("Duplicate observer", 1, observable.countObservers()); - - Observable o = new Observable(); - try { - o.addObserver(null); - fail("Expected adding a null observer to throw a NPE."); - } catch (NullPointerException ex) { - // expected; - } catch (Throwable ex) { - fail("Did not expect adding a new observer to throw a " - + ex.getClass().getName()); - } - } - - /** - * java.util.Observable#countObservers() - */ - public void test_countObservers() { - // Test for method int java.util.Observable.countObservers() - assertEquals("New observable had > 0 observers", 0, observable - .countObservers()); - observable.addObserver(new TestObserver()); - assertEquals("Observable with observer returned other than 1", 1, observable - .countObservers()); - } - - /** - * java.util.Observable#deleteObserver(java.util.Observer) - */ - public void test_deleteObserverLjava_util_Observer() { - // Test for method void - // java.util.Observable.deleteObserver(java.util.Observer) - observable.addObserver(observer = new TestObserver()); - observable.deleteObserver(observer); - assertEquals("Failed to delete observer", - 0, observable.countObservers()); - observable.deleteObserver(observer); - observable.deleteObserver(null); - } - - /** - * java.util.Observable#deleteObservers() - */ - public void test_deleteObservers() { - // Test for method void java.util.Observable.deleteObservers() - observable.addObserver(new TestObserver()); - observable.addObserver(new TestObserver()); - observable.addObserver(new TestObserver()); - observable.addObserver(new TestObserver()); - observable.addObserver(new TestObserver()); - observable.addObserver(new TestObserver()); - observable.addObserver(new TestObserver()); - observable.addObserver(new TestObserver()); - observable.deleteObservers(); - assertEquals("Failed to delete observers", - 0, observable.countObservers()); - } - - /** - * java.util.Observable#hasChanged() - */ - public void test_hasChanged() { - assertFalse(observable.hasChanged()); - observable.addObserver(observer = new TestObserver()); - observable.doChange(); - assertTrue(observable.hasChanged()); - } - - public void test_clearChanged() { - assertFalse(observable.hasChanged()); - observable.addObserver(observer = new TestObserver()); - observable.doChange(); - assertTrue(observable.hasChanged()); - observable.clearChange(); - assertFalse(observable.hasChanged()); - } - - /** - * java.util.Observable#notifyObservers() - */ - public void test_notifyObservers() { - // Test for method void java.util.Observable.notifyObservers() - observable.addObserver(observer = new TestObserver()); - observable.notifyObservers(); - assertEquals("Notified when unchnaged", 0, ((TestObserver) observer) - .updateCount()); - ((TestObservable) observable).doChange(); - observable.notifyObservers(); - assertEquals("Failed to notify", - 1, ((TestObserver) observer).updateCount()); - - DeleteTestObserver observer1, observer2; - observable.deleteObservers(); - observable.addObserver(observer1 = new DeleteTestObserver(false)); - observable.addObserver(observer2 = new DeleteTestObserver(false)); - observable.doChange(); - observable.notifyObservers(); - assertTrue("Failed to notify all", observer1.updateCount() == 1 - && observer2.updateCount() == 1); - assertEquals("Failed to delete all", 0, observable.countObservers()); - - observable.addObserver(observer1 = new DeleteTestObserver(false)); - observable.addObserver(observer2 = new DeleteTestObserver(false)); - observable.doChange(); - observable.notifyObservers(); - assertTrue("Failed to notify all 2", observer1.updateCount() == 1 - && observer2.updateCount() == 1); - assertEquals("Failed to delete all 2", 0, observable.countObservers()); - } - - /** - * java.util.Observable#notifyObservers(java.lang.Object) - */ - public void test_notifyObserversLjava_lang_Object() { - // Test for method void - // java.util.Observable.notifyObservers(java.lang.Object) - Object obj; - observable.addObserver(observer = new TestObserver()); - observable.notifyObservers(); - assertEquals("Notified when unchanged", 0, ((TestObserver) observer) - .updateCount()); - ((TestObservable) observable).doChange(); - observable.notifyObservers(obj = new Object()); - assertEquals("Failed to notify", - 1, ((TestObserver) observer).updateCount()); - assertTrue("Failed to pass Object arg", ((TestObserver) observer).objv - .elementAt(0).equals(obj)); - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - observable = new TestObservable(); - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/util/PropertyResourceBundleTest.java b/luni/src/test/java/tests/api/java/util/PropertyResourceBundleTest.java deleted file mode 100644 index bc6a4fe..0000000 --- a/luni/src/test/java/tests/api/java/util/PropertyResourceBundleTest.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.Enumeration; -import java.util.MissingResourceException; -import java.util.PropertyResourceBundle; -import java.util.Vector; - -public class PropertyResourceBundleTest extends junit.framework.TestCase { - - static PropertyResourceBundle prb; - - /** - * java.util.PropertyResourceBundle#PropertyResourceBundle(java.io.InputStream) - */ - public void test_ConstructorLjava_io_InputStream() { - // Test for method java.util.PropertyResourceBundle(java.io.InputStream) - assertTrue("Used to test", true); - } - - /** - * java.util.PropertyResourceBundle#getKeys() - */ - public void test_getKeys() { - Enumeration keyEnum = prb.getKeys(); - Vector test = new Vector(); - int keyCount = 0; - while (keyEnum.hasMoreElements()) { - test.addElement(keyEnum.nextElement()); - keyCount++; - } - - assertEquals("Returned the wrong number of keys", 2, keyCount); - assertTrue("Returned the wrong keys", test.contains("p1") - && test.contains("p2")); - } - - /** - * java.util.PropertyResourceBundle#handleGetObject(java.lang.String) - */ - public void test_handleGetObjectLjava_lang_String() { - // Test for method java.lang.Object - // java.util.PropertyResourceBundle.handleGetObject(java.lang.String) - try { - assertTrue("Returned incorrect objects", prb.getObject("p1") - .equals("one") - && prb.getObject("p2").equals("two")); - } catch (MissingResourceException e) { - fail( - "Threw MisingResourceException for a key contained in the bundle"); - } - try { - prb.getObject("Not in the bundle"); - } catch (MissingResourceException e) { - return; - } - fail( - "Failed to throw MissingResourceException for object not in the bundle"); - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - java.io.InputStream propertiesStream = new java.io.ByteArrayInputStream( - "p1=one\np2=two".getBytes()); - try { - prb = new PropertyResourceBundle(propertiesStream); - } catch (java.io.IOException e) { - fail( - "Contruction of PropertyResourceBundle threw IOException"); - } - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/util/RandomTest.java b/luni/src/test/java/tests/api/java/util/RandomTest.java deleted file mode 100644 index bb72191..0000000 --- a/luni/src/test/java/tests/api/java/util/RandomTest.java +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.Random; - -public class RandomTest extends junit.framework.TestCase { - - Random r; - - /** - * java.util.Random#Random() - */ - public void test_Constructor() { - // Test for method java.util.Random() - assertTrue("Used to test", true); - } - - /** - * java.util.Random#Random(long) - */ - public void test_ConstructorJ() { - Random r = new Random(8409238L); - Random r2 = new Random(8409238L); - for (int i = 0; i < 100; i++) - assertTrue("Values from randoms with same seed don't match", r - .nextInt() == r2.nextInt()); - } - - /** - * java.util.Random#nextBoolean() - */ - public void test_nextBoolean() { - // Test for method boolean java.util.Random.nextBoolean() - boolean falseAppeared = false, trueAppeared = false; - for (int counter = 0; counter < 100; counter++) - if (r.nextBoolean()) - trueAppeared = true; - else - falseAppeared = true; - assertTrue("Calling nextBoolean() 100 times resulted in all trues", - falseAppeared); - assertTrue("Calling nextBoolean() 100 times resulted in all falses", - trueAppeared); - } - - /** - * java.util.Random#nextBytes(byte[]) - */ - public void test_nextBytes$B() { - // Test for method void java.util.Random.nextBytes(byte []) - boolean someDifferent = false; - byte[] randomBytes = new byte[100]; - r.nextBytes(randomBytes); - byte firstByte = randomBytes[0]; - for (int counter = 1; counter < randomBytes.length; counter++) - if (randomBytes[counter] != firstByte) - someDifferent = true; - assertTrue( - "nextBytes() returned an array of length 100 of the same byte", - someDifferent); - } - - /** - * java.util.Random#nextDouble() - */ - public void test_nextDouble() { - // Test for method double java.util.Random.nextDouble() - double lastNum = r.nextDouble(); - double nextNum; - boolean someDifferent = false; - boolean inRange = true; - for (int counter = 0; counter < 100; counter++) { - nextNum = r.nextDouble(); - if (nextNum != lastNum) - someDifferent = true; - if (!(0 <= nextNum && nextNum < 1.0)) - inRange = false; - lastNum = nextNum; - } - assertTrue("Calling nextDouble 100 times resulted in same number", - someDifferent); - assertTrue( - "Calling nextDouble resulted in a number out of range [0,1)", - inRange); - } - - /** - * java.util.Random#nextFloat() - */ - public void test_nextFloat() { - // Test for method float java.util.Random.nextFloat() - float lastNum = r.nextFloat(); - float nextNum; - boolean someDifferent = false; - boolean inRange = true; - for (int counter = 0; counter < 100; counter++) { - nextNum = r.nextFloat(); - if (nextNum != lastNum) - someDifferent = true; - if (!(0 <= nextNum && nextNum < 1.0)) - inRange = false; - lastNum = nextNum; - } - assertTrue("Calling nextFloat 100 times resulted in same number", - someDifferent); - assertTrue("Calling nextFloat resulted in a number out of range [0,1)", - inRange); - } - - /** - * java.util.Random#nextGaussian() - */ - public void test_nextGaussian() { - // Test for method double java.util.Random.nextGaussian() - double lastNum = r.nextGaussian(); - double nextNum; - boolean someDifferent = false; - boolean someInsideStd = false; - for (int counter = 0; counter < 100; counter++) { - nextNum = r.nextGaussian(); - if (nextNum != lastNum) - someDifferent = true; - if (-1.0 <= nextNum && nextNum <= 1.0) - someInsideStd = true; - lastNum = nextNum; - } - assertTrue("Calling nextGaussian 100 times resulted in same number", - someDifferent); - assertTrue( - "Calling nextGaussian 100 times resulted in no number within 1 std. deviation of mean", - someInsideStd); - } - - /** - * java.util.Random#nextInt() - */ - public void test_nextInt() { - // Test for method int java.util.Random.nextInt() - int lastNum = r.nextInt(); - int nextNum; - boolean someDifferent = false; - for (int counter = 0; counter < 100; counter++) { - nextNum = r.nextInt(); - if (nextNum != lastNum) - someDifferent = true; - lastNum = nextNum; - } - assertTrue("Calling nextInt 100 times resulted in same number", - someDifferent); - } - - /** - * java.util.Random#nextInt(int) - */ - public void test_nextIntI() { - // Test for method int java.util.Random.nextInt(int) - final int range = 10; - int lastNum = r.nextInt(range); - int nextNum; - boolean someDifferent = false; - boolean inRange = true; - for (int counter = 0; counter < 100; counter++) { - nextNum = r.nextInt(range); - if (nextNum != lastNum) - someDifferent = true; - if (!(0 <= nextNum && nextNum < range)) - inRange = false; - lastNum = nextNum; - } - assertTrue("Calling nextInt (range) 100 times resulted in same number", - someDifferent); - assertTrue( - "Calling nextInt (range) resulted in a number outside of [0, range)", - inRange); - - } - - /** - * java.util.Random#nextLong() - */ - public void test_nextLong() { - // Test for method long java.util.Random.nextLong() - long lastNum = r.nextLong(); - long nextNum; - boolean someDifferent = false; - for (int counter = 0; counter < 100; counter++) { - nextNum = r.nextLong(); - if (nextNum != lastNum) - someDifferent = true; - lastNum = nextNum; - } - assertTrue("Calling nextLong 100 times resulted in same number", - someDifferent); - } - - /** - * java.util.Random#setSeed(long) - */ - public void test_setSeedJ() { - // Test for method void java.util.Random.setSeed(long) - long[] randomArray = new long[100]; - boolean someDifferent = false; - final long firstSeed = 1000; - long aLong, anotherLong, yetAnotherLong; - Random aRandom = new Random(); - Random anotherRandom = new Random(); - Random yetAnotherRandom = new Random(); - aRandom.setSeed(firstSeed); - anotherRandom.setSeed(firstSeed); - for (int counter = 0; counter < randomArray.length; counter++) { - aLong = aRandom.nextLong(); - anotherLong = anotherRandom.nextLong(); - assertTrue( - "Two randoms with same seeds gave differing nextLong values", - aLong == anotherLong); - yetAnotherLong = yetAnotherRandom.nextLong(); - randomArray[counter] = aLong; - if (aLong != yetAnotherLong) - someDifferent = true; - } - assertTrue( - "Two randoms with the different seeds gave the same chain of values", - someDifferent); - aRandom.setSeed(firstSeed); - for (int counter = 0; counter < randomArray.length; counter++) - assertTrue( - "Reseting a random to its old seed did not result in the same chain of values as it gave before", - aRandom.nextLong() == randomArray[counter]); - } - - class Mock_Random extends Random { - boolean nextCalled = false; - - public boolean getFlag () { - boolean retVal = nextCalled; - nextCalled = false; - return retVal; - } - - @Override - protected int next(int bits) { - nextCalled = true; - return super.next(bits); - } - } - - public void test_next() { - Mock_Random mr = new Mock_Random(); - assertFalse(mr.getFlag()); - mr.nextBoolean(); - assertTrue(mr.getFlag()); - mr.nextBytes(new byte[10]); - assertTrue(mr.getFlag()); - mr.nextDouble(); - assertTrue(mr.getFlag()); - mr.nextFloat(); - assertTrue(mr.getFlag()); - mr.nextGaussian(); - assertTrue(mr.getFlag()); - mr.nextInt(); - assertTrue(mr.getFlag()); - mr.nextInt(10); - assertTrue(mr.getFlag()); - mr.nextLong(); - assertTrue(mr.getFlag()); - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - r = new Random(); - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/util/ResourceBundleTest.java b/luni/src/test/java/tests/api/java/util/ResourceBundleTest.java deleted file mode 100644 index 587a549..0000000 --- a/luni/src/test/java/tests/api/java/util/ResourceBundleTest.java +++ /dev/null @@ -1,398 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import dalvik.annotation.KnownFailure; -import java.io.File; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.Enumeration; -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.ResourceBundle; -import java.util.StringTokenizer; -import java.util.Vector; -import tests.api.java.util.support.B; -import tests.support.resource.Support_Resources; - -public class ResourceBundleTest extends junit.framework.TestCase { - - public void test_getCandidateLocales() throws Exception { - ResourceBundle.Control c = ResourceBundle.Control.getControl(ResourceBundle.Control.FORMAT_DEFAULT); - assertEquals("[en_US, en, ]", c.getCandidateLocales("base", Locale.US).toString()); - assertEquals("[de_CH, de, ]", c.getCandidateLocales("base", new Locale("de", "CH")).toString()); - } - - /** - * java.util.ResourceBundle#getBundle(java.lang.String, - * java.util.Locale) - */ - public void test_getBundleLjava_lang_StringLjava_util_Locale() { - ResourceBundle bundle; - String name = "tests.support.Support_TestResource"; - Locale defLocale = Locale.getDefault(); - - Locale.setDefault(new Locale("en", "US")); - bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR")); - assertEquals("Wrong bundle fr_FR_VAR", "frFRVARValue4", bundle.getString("parent4")); - - bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "v1")); - assertEquals("Wrong bundle fr_FR_v1", "frFRValue4", bundle.getString("parent4")); - - bundle = ResourceBundle.getBundle(name, new Locale("fr", "US", "VAR")); - assertEquals("Wrong bundle fr_US_var", "frValue4", bundle.getString("parent4")); - - bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "VAR")); - assertEquals("Wrong bundle de_FR_var", "enUSValue4", bundle.getString("parent4")); - - Locale.setDefault(new Locale("fr", "FR", "VAR")); - bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "v1")); - assertEquals("Wrong bundle de_FR_var 2", "frFRVARValue4", bundle.getString("parent4")); - - Locale.setDefault(new Locale("de", "US")); - bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "var")); - assertEquals("Wrong bundle de_FR_var 2", "parentValue4", bundle.getString("parent4") - ); - - try { - ResourceBundle.getBundle(null, Locale.US); - fail("NullPointerException expected"); - } catch (NullPointerException ee) { - //expected - } - try { - ResourceBundle.getBundle("blah", (Locale) null); - fail("NullPointerException expected"); - } catch (NullPointerException ee) { - //expected - } - - - try { - ResourceBundle.getBundle("", new Locale("xx", "yy")); - fail("MissingResourceException expected"); - } catch (MissingResourceException ee) { - //expected - } - } - - /** - * java.util.ResourceBundle#getBundle(java.lang.String, - * java.util.Locale, java.lang.ClassLoader) - */ - @KnownFailure("It's not allowed to pass null as parent class loader to" - + " a new ClassLoader anymore. Maybe we need to change" - + " URLClassLoader to allow this? It's not specified.") - public void test_getBundleLjava_lang_StringLjava_util_LocaleLjava_lang_ClassLoader() { - String classPath = System.getProperty("java.class.path"); - StringTokenizer tok = new StringTokenizer(classPath, File.pathSeparator); - Vector<URL> urlVec = new Vector<URL>(); - String resPackage = Support_Resources.RESOURCE_PACKAGE; - try { - while (tok.hasMoreTokens()) { - String path = tok.nextToken(); - String url; - if (new File(path).isDirectory()) - url = "file:" + path + resPackage + "subfolder/"; - else - url = "jar:file:" + path + "!" + resPackage + "subfolder/"; - urlVec.addElement(new URL(url)); - } - } catch (MalformedURLException e) { - } - URL[] urls = new URL[urlVec.size()]; - for (int i = 0; i < urlVec.size(); i++) - urls[i] = urlVec.elementAt(i); - URLClassLoader loader = new URLClassLoader(urls, null); - - String name = Support_Resources.RESOURCE_PACKAGE_NAME - + ".hyts_resource"; - ResourceBundle bundle = ResourceBundle.getBundle(name, Locale - .getDefault()); - assertEquals("Wrong value read", "parent", bundle.getString("property")); - bundle = ResourceBundle.getBundle(name, Locale.getDefault(), loader); - assertEquals("Wrong cached value", - "resource", bundle.getString("property")); - - try { - ResourceBundle.getBundle(null, Locale.getDefault(), loader); - fail("NullPointerException expected"); - } catch (NullPointerException ee) { - //expected - } - - try { - ResourceBundle.getBundle(name, null, loader); - fail("NullPointerException expected"); - } catch (NullPointerException ee) { - //expected - } - - try { - ResourceBundle.getBundle(name, Locale.getDefault(), (ClassLoader) null); - fail("NullPointerException expected"); - } catch (NullPointerException ee) { - //expected - } - - try { - ResourceBundle.getBundle("", Locale.getDefault(), loader); - fail("MissingResourceException expected"); - } catch (MissingResourceException ee) { - //expected - } - - // Regression test for Harmony-3823 - B bb = new B(); - String s = bb.find("nonexistent"); - s = bb.find("name"); - assertEquals("Wrong property got", "Name", s); - } - - /** - * java.util.ResourceBundle#getString(java.lang.String) - */ - public void test_getStringLjava_lang_String() { - ResourceBundle bundle; - String name = "tests.support.Support_TestResource"; - Locale.setDefault(new Locale("en", "US")); - bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR")); - assertEquals("Wrong value parent4", - "frFRVARValue4", bundle.getString("parent4")); - assertEquals("Wrong value parent3", - "frFRValue3", bundle.getString("parent3")); - assertEquals("Wrong value parent2", - "frValue2", bundle.getString("parent2")); - assertEquals("Wrong value parent1", - "parentValue1", bundle.getString("parent1")); - assertEquals("Wrong value child3", - "frFRVARChildValue3", bundle.getString("child3")); - assertEquals("Wrong value child2", - "frFRVARChildValue2", bundle.getString("child2")); - assertEquals("Wrong value child1", - "frFRVARChildValue1", bundle.getString("child1")); - - try { - bundle.getString(null); - fail("NullPointerException expected"); - } catch (NullPointerException ee) { - //expected - } - - try { - bundle.getString(""); - fail("MissingResourceException expected"); - } catch (MissingResourceException ee) { - //expected - } - - try { - bundle.getString("IntegerVal"); - fail("ClassCastException expected"); - } catch (ClassCastException ee) { - //expected - } - } - public void test_getBundle_getClassName() { - // Regression test for Harmony-1759 - Locale locale = Locale.GERMAN; - String nonExistentBundle = "Non-ExistentBundle"; - try { - ResourceBundle.getBundle(nonExistentBundle, locale, this.getClass() - .getClassLoader()); - fail("MissingResourceException expected!"); - } catch (MissingResourceException e) { - assertEquals(nonExistentBundle + "_" + locale, e.getClassName()); - } - - try { - ResourceBundle.getBundle(nonExistentBundle, locale); - fail("MissingResourceException expected!"); - } catch (MissingResourceException e) { - assertEquals(nonExistentBundle + "_" + locale, e.getClassName()); - } - - locale = Locale.getDefault(); - try { - ResourceBundle.getBundle(nonExistentBundle); - fail("MissingResourceException expected!"); - } catch (MissingResourceException e) { - assertEquals(nonExistentBundle + "_" + locale, e.getClassName()); - } - } - - class Mock_ResourceBundle extends ResourceBundle { - @Override - public Enumeration<String> getKeys() { - return null; - } - - @Override - protected Object handleGetObject(String key) { - return null; - } - } - - public void test_constructor() { - assertNotNull(new Mock_ResourceBundle()); - } - - public void test_getLocale() { - ResourceBundle bundle; - String name = "tests.support.Support_TestResource"; - Locale loc = Locale.getDefault(); - Locale.setDefault(new Locale("en", "US")); - - bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR")); - assertEquals("fr_FR_VAR", bundle.getLocale().toString()); - - bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "v1")); - assertEquals("fr_FR", bundle.getLocale().toString()); - - bundle = ResourceBundle.getBundle(name, new Locale("fr", "US", "VAR")); - assertEquals("fr", bundle.getLocale().toString()); - - bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "VAR")); - assertEquals("en_US", bundle.getLocale().toString()); - - bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "v1")); - assertEquals("en_US", bundle.getLocale().toString()); - - bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "var")); - assertEquals("en_US", bundle.getLocale().toString()); - - Locale.setDefault(loc); - } - - public void test_getObjectLjava_lang_String() { - ResourceBundle bundle; - String name = "tests.support.Support_TestResource"; - Locale.setDefault(new Locale("en", "US")); - bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR")); - assertEquals("Wrong value parent4", - "frFRVARValue4", (String)bundle.getObject("parent4")); - assertEquals("Wrong value parent3", - "frFRValue3", (String)bundle.getObject("parent3")); - assertEquals("Wrong value parent2", - "frValue2", (String) bundle.getObject("parent2")); - assertEquals("Wrong value parent1", - "parentValue1", (String)bundle.getObject("parent1")); - assertEquals("Wrong value child3", - "frFRVARChildValue3", (String)bundle.getObject("child3")); - assertEquals("Wrong value child2", - "frFRVARChildValue2", (String) bundle.getObject("child2")); - assertEquals("Wrong value child1", - "frFRVARChildValue1", (String)bundle.getObject("child1")); - assertEquals("Wrong value IntegerVal", - 1, bundle.getObject("IntegerVal")); - - try { - bundle.getObject(null); - fail("NullPointerException expected"); - } catch (NullPointerException ee) { - //expected - } - - try { - bundle.getObject(""); - fail("MissingResourceException expected"); - } catch (MissingResourceException ee) { - //expected - } - } - - public void test_getStringArrayLjava_lang_String() { - ResourceBundle bundle; - String name = "tests.support.Support_TestResource"; - Locale.setDefault(new Locale("en", "US")); - bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR")); - - String[] array = bundle.getStringArray("StringArray"); - for(int i = 0; i < array.length; i++) { - assertEquals("Str" + (i + 1), array[i]); - } - - try { - bundle.getStringArray(null); - fail("NullPointerException expected"); - } catch (NullPointerException ee) { - //expected - } - - try { - bundle.getStringArray(""); - fail("MissingResourceException expected"); - } catch (MissingResourceException ee) { - //expected - } - - try { - bundle.getStringArray("IntegerVal"); - fail("ClassCastException expected"); - } catch (ClassCastException ee) { - //expected - } - } - - public void test_getBundleLjava_lang_String() { - ResourceBundle bundle; - String name = "tests.support.Support_TestResource"; - Locale defLocale = Locale.getDefault(); - - Locale.setDefault(new Locale("en", "US")); - bundle = ResourceBundle.getBundle(name); - assertEquals("enUSValue4", bundle.getString("parent4")); - - Locale.setDefault(new Locale("fr", "FR", "v1")); - bundle = ResourceBundle.getBundle(name); - assertEquals("Wrong bundle fr_FR_v1", "frFRValue4", bundle.getString("parent4")); - - Locale.setDefault(new Locale("fr", "US", "VAR")); - bundle = ResourceBundle.getBundle(name); - assertEquals("Wrong bundle fr_US_var", "frValue4", bundle.getString("parent4")); - - Locale.setDefault(new Locale("de", "FR", "VAR")); - bundle = ResourceBundle.getBundle(name); - assertEquals("Wrong bundle de_FR_var", "parentValue4", bundle.getString("parent4")); - - Locale.setDefault(new Locale("de", "FR", "v1")); - bundle = ResourceBundle.getBundle(name); - assertEquals("Wrong bundle de_FR_var 2", "parentValue4", bundle.getString("parent4")); - - Locale.setDefault(new Locale("de", "FR", "var")); - bundle = ResourceBundle.getBundle(name); - assertEquals("Wrong bundle de_FR_var 2", "parentValue4", bundle.getString("parent4")); - - try { - ResourceBundle.getBundle(null); - fail("NullPointerException expected"); - } catch (NullPointerException ee) { - //expected - } - - try { - ResourceBundle.getBundle(""); - fail("MissingResourceException expected"); - } catch (MissingResourceException ee) { - //expected - } - - Locale.setDefault(defLocale); - } -} diff --git a/luni/src/test/java/tests/api/java/util/SampleBundleClass.java b/luni/src/test/java/tests/api/java/util/SampleBundleClass.java deleted file mode 100644 index ceb0901..0000000 --- a/luni/src/test/java/tests/api/java/util/SampleBundleClass.java +++ /dev/null @@ -1,43 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -/** - * Part of the ResourceBundleTest - */ -public class SampleBundleClass { - - private static SampleBundleClass singleton; - private static ResourceBundle bundle; - - public SampleBundleClass() { - super(); - if (singleton != null) { - throw new RuntimeException(); - } - singleton = this; - try { - bundle = ResourceBundle.getBundle("tests.api.simple.SampleBundleClass"); - } catch (MissingResourceException x) { - System.out.println("Missing resource"); - bundle = null; - } - } -} diff --git a/luni/src/test/java/tests/api/java/util/SimpleTimeZoneTest.java b/luni/src/test/java/tests/api/java/util/SimpleTimeZoneTest.java deleted file mode 100644 index eeb5b30..0000000 --- a/luni/src/test/java/tests/api/java/util/SimpleTimeZoneTest.java +++ /dev/null @@ -1,838 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.SimpleTimeZone; -import java.util.TimeZone; - -public class SimpleTimeZoneTest extends junit.framework.TestCase { - - SimpleTimeZone st1; - - SimpleTimeZone st2; - - /** - * java.util.SimpleTimeZone#SimpleTimeZone(int, java.lang.String) - */ - public void test_ConstructorILjava_lang_String() { - // Test for method java.util.SimpleTimeZone(int, java.lang.String) - - SimpleTimeZone st = new SimpleTimeZone(1000, "TEST"); - assertEquals("Incorrect TZ constructed", "TEST", st.getID()); - assertTrue("Incorrect TZ constructed: " + "returned wrong offset", st - .getRawOffset() == 1000); - assertTrue("Incorrect TZ constructed" + "using daylight savings", !st - .useDaylightTime()); - } - - /** - * java.util.SimpleTimeZone#SimpleTimeZone(int, java.lang.String, - * int, int, int, int, int, int, int, int) - */ - public void test_ConstructorILjava_lang_StringIIIIIIII() { - // Test for method java.util.SimpleTimeZone(int, java.lang.String, int, - // int, int, int, int, int, int, int) - SimpleTimeZone st = new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER, - 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY, - 0); - assertTrue("Incorrect TZ constructed", st - .inDaylightTime(new GregorianCalendar(1998, Calendar.NOVEMBER, - 13).getTime())); - assertTrue("Incorrect TZ constructed", !(st - .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER, - 13).getTime()))); - assertEquals("Incorrect TZ constructed", "TEST", st.getID()); - assertEquals("Incorrect TZ constructed", 1000, st.getRawOffset()); - assertTrue("Incorrect TZ constructed", st.useDaylightTime()); - - try { - new SimpleTimeZone(1000, "TEST", 12, - 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY, - 0); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER, - 10, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY, - 0); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER, - 1, 10, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY, - 0); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - new SimpleTimeZone(1000, "TEST", Calendar.DECEMBER, - 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -10, Calendar.SUNDAY, - 0); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - } - - /** - * java.util.SimpleTimeZone#SimpleTimeZone(int, java.lang.String, - * int, int, int, int, int, int, int, int, int) - */ - public void test_ConstructorILjava_lang_StringIIIIIIIII() { - // Test for method java.util.SimpleTimeZone(int, java.lang.String, int, - // int, int, int, int, int, int, int, int) - SimpleTimeZone st = new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER, - 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY, - 0, 1000 * 60 * 60); - assertTrue("Incorrect TZ constructed", st - .inDaylightTime(new GregorianCalendar(1998, Calendar.NOVEMBER, - 13).getTime())); - assertTrue("Incorrect TZ constructed", !(st - .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER, - 13).getTime()))); - assertEquals("Incorrect TZ constructed", "TEST", st.getID()); - assertEquals("Incorrect TZ constructed", 1000, st.getRawOffset()); - assertTrue("Incorrect TZ constructed", st.useDaylightTime()); - assertTrue("Incorrect TZ constructed", - st.getDSTSavings() == 1000 * 60 * 60); - - try { - new SimpleTimeZone(1000, "TEST", 12, - 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY, - 0, 1000 * 60 * 60); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER, - 10, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY, - 0, 1000 * 60 * 60); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER, - 1, 10, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY, - 0, 1000 * 60 * 60); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - new SimpleTimeZone(1000, "TEST", Calendar.DECEMBER, - 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -10, Calendar.SUNDAY, - 0, 1000 * 60 * 60); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - } - - /** - * java.util.SimpleTimeZone#SimpleTimeZone(int, java.lang.String, - * int, int, int, int, int, int, int, int, int, int, int) - */ - public void test_ConstructorILjava_lang_StringIIIIIIIIIII() { - // Test for method java.util.SimpleTimeZone(int, java.lang.String, int, - // int, int, int, int, int, int, int, int, int, int) - // TODO : Implement test - //Regression for HARMONY-1241 - assertNotNull(new SimpleTimeZone( - TimeZone.LONG, - "Europe/Paris", - SimpleTimeZone.STANDARD_TIME, - SimpleTimeZone.STANDARD_TIME, - SimpleTimeZone.UTC_TIME, - SimpleTimeZone.WALL_TIME, - SimpleTimeZone.WALL_TIME, - TimeZone.SHORT, - SimpleTimeZone.STANDARD_TIME, - TimeZone.LONG, - SimpleTimeZone.UTC_TIME, - SimpleTimeZone.STANDARD_TIME, - TimeZone.LONG)); - //seems RI doesn't check the startTimeMode and endTimeMode at all - //this behavior is contradicts with spec - assertNotNull(new SimpleTimeZone( - TimeZone.LONG, - "Europe/Paris", - SimpleTimeZone.STANDARD_TIME, - SimpleTimeZone.STANDARD_TIME, - SimpleTimeZone.UTC_TIME, - SimpleTimeZone.WALL_TIME, - Integer.MAX_VALUE, - TimeZone.SHORT, - SimpleTimeZone.STANDARD_TIME, - TimeZone.LONG, - SimpleTimeZone.UTC_TIME, - Integer.MIN_VALUE, - TimeZone.LONG)); - - try { - new SimpleTimeZone(1000, "TEST", 12, - 1, Calendar.SUNDAY, 0, Integer.MAX_VALUE, Calendar.NOVEMBER, -1, Calendar.SUNDAY, - 0, Integer.MAX_VALUE, 1000 * 60 * 60); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER, - 10, Calendar.SUNDAY, 0, Integer.MAX_VALUE, Calendar.NOVEMBER, -1, Calendar.SUNDAY, - 0, Integer.MAX_VALUE, 1000 * 60 * 60); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER, - 1, 10, 0, Calendar.NOVEMBER, Integer.MAX_VALUE, -1, Calendar.SUNDAY, - 0, Integer.MAX_VALUE, 1000 * 60 * 60); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - new SimpleTimeZone(1000, "TEST", Calendar.DECEMBER, - 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, Integer.MAX_VALUE, -10, Calendar.SUNDAY, - 0, Integer.MAX_VALUE, 1000 * 60 * 60); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - } - - /** - * java.util.SimpleTimeZone#clone() - */ - public void test_clone() { - // Test for method java.lang.Object java.util.SimpleTimeZone.clone() - SimpleTimeZone st1 = new SimpleTimeZone(1000, "TEST", - Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, - -1, Calendar.SUNDAY, 0); - SimpleTimeZone stA = new SimpleTimeZone(1, "Gah"); - assertTrue("Clone resulted in same reference", st1.clone() != st1); - assertTrue("Clone resulted in unequal object", ((SimpleTimeZone) st1 - .clone()).equals(st1)); - assertTrue("Clone resulted in same reference", stA.clone() != stA); - assertTrue("Clone resulted in unequal object", ((SimpleTimeZone) stA - .clone()).equals(stA)); - } - - /** - * java.util.SimpleTimeZone#equals(java.lang.Object) - */ - public void test_equalsLjava_lang_Object() { - // Test for method boolean - // java.util.SimpleTimeZone.equals(java.lang.Object) - TimeZone tz = TimeZone.getTimeZone("EST"); - st1 = new SimpleTimeZone(tz.getRawOffset(), "EST"); - st2 = new SimpleTimeZone(0, "EST"); - assertFalse(st1.equals(st2)); - st1.setRawOffset(st2.getRawOffset()); - assertTrue(st1.equals(st2)); - } - - /** - * java.util.SimpleTimeZone#getDSTSavings() - */ - public void test_getDSTSavings() { - // Test for method int java.util.SimpleTimeZone.getDSTSavings() - st1 = new SimpleTimeZone(0, "TEST"); - - assertEquals("Non-zero default daylight savings", - 0, st1.getDSTSavings()); - st1.setStartRule(0, 1, 1, 1); - st1.setEndRule(11, 1, 1, 1); - - assertEquals("Incorrect default daylight savings", - 3600000, st1.getDSTSavings()); - st1 = new SimpleTimeZone(-5 * 3600000, "EST", Calendar.APRIL, 1, - -Calendar.SUNDAY, 2 * 3600000, Calendar.OCTOBER, -1, - Calendar.SUNDAY, 2 * 3600000, 7200000); - assertEquals("Incorrect daylight savings from constructor", 7200000, st1 - .getDSTSavings()); - - } - - /** - * java.util.SimpleTimeZone#getOffset(int, int, int, int, int, int) - */ - public void test_getOffsetIIIIII() { - // Test for method int java.util.SimpleTimeZone.getOffset(int, int, int, - // int, int, int) -// TimeZone st1 = TimeZone.getTimeZone("EST"); - st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST"); - assertTrue("Incorrect offset returned", st1.getOffset( - GregorianCalendar.AD, 1998, Calendar.NOVEMBER, 11, - Calendar.WEDNESDAY, 0) == -(5 * 60 * 60 * 1000)); - - st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST"); - assertEquals("Incorrect offset returned", -(5 * 60 * 60 * 1000), st1 - .getOffset(GregorianCalendar.AD, 1998, Calendar.JUNE, 11, - Calendar.THURSDAY, 0)); - - // Regression for HARMONY-5459 - st1 = new SimpleTimeZone(TimeZone.getDefault().getRawOffset(), TimeZone.getDefault().getID()); - int fourHours = 4*60*60*1000; - st1.setRawOffset(fourHours); - assertEquals(fourHours, st1.getOffset(1, 2099, 01, 1, 5, 0)); - - try { - st1.getOffset(-1, 2099, 01, 1, 5, 0); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - st1.getOffset(1, 2099, 15, 1, 5, 0); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - st1.getOffset(1, 2099, 01, 100, 5, 0); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - st1.getOffset(1, 2099, 01, 1, 50, 0); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - st1.getOffset(1, 2099, 01, 1, 5, -10); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - } - - /** - * java.util.SimpleTimeZone#getRawOffset() - */ - public void test_getRawOffset() { - // Test for method int java.util.SimpleTimeZone.getRawOffset() - st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST"); - assertTrue("Incorrect offset returned", - st1.getRawOffset() == -(5 * 60 * 60 * 1000)); - - } - - /** - * java.util.SimpleTimeZone#hashCode() - */ - public void test_hashCode() { - // Test for method int java.util.SimpleTimeZone.hashCode() - // For lack of a better test. - st1 = new SimpleTimeZone(-5 * 3600000, "EST", Calendar.APRIL, 1, - -Calendar.SUNDAY, 2 * 3600000, Calendar.OCTOBER, -1, - Calendar.SUNDAY, 2 * 3600000); - assertTrue(TimeZone.getTimeZone("EST").hashCode() != 0); - assertTrue(st1.hashCode() != 0); - } - - /** - * java.util.SimpleTimeZone#hasSameRules(java.util.TimeZone) - */ - public void test_hasSameRulesLjava_util_TimeZone() { - // Test for method boolean - // java.util.SimpleTimeZone.hasSameRules(java.util.TimeZone) - SimpleTimeZone st = new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER, - 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY, - 0); - SimpleTimeZone sameAsSt = new SimpleTimeZone(1000, "REST", - Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, - -1, Calendar.SUNDAY, 0); - SimpleTimeZone notSameAsSt = new SimpleTimeZone(1000, "PEST", - Calendar.NOVEMBER, 2, Calendar.SUNDAY, 0, Calendar.NOVEMBER, - -1, Calendar.SUNDAY, 0); - assertTrue("Time zones have same rules but return false", st - .hasSameRules(sameAsSt)); - assertTrue("Time zones have different rules but return true", !st - .hasSameRules(notSameAsSt)); - } - - /** - * java.util.SimpleTimeZone#inDaylightTime(java.util.Date) - */ - public void test_inDaylightTimeLjava_util_Date() { - // Test for method boolean - // java.util.SimpleTimeZone.inDaylightTime(java.util.Date) - TimeZone tz = TimeZone.getTimeZone("EST"); - SimpleTimeZone zone = new SimpleTimeZone(tz.getRawOffset(), "EST", - Calendar.APRIL, 1, -Calendar.SUNDAY, 7200000, Calendar.OCTOBER, -1, Calendar.SUNDAY, 7200000, 3600000); - GregorianCalendar gc = new GregorianCalendar(1998, Calendar.JUNE, 11); - - assertTrue("Returned incorrect daylight value1", zone.inDaylightTime(gc - .getTime())); - gc = new GregorianCalendar(1998, Calendar.NOVEMBER, 11); - assertTrue("Returned incorrect daylight value2", !(zone - .inDaylightTime(gc.getTime()))); - gc = new GregorianCalendar(zone); - gc.set(1999, Calendar.APRIL, 4, 1, 59, 59); - assertTrue("Returned incorrect daylight value3", !(zone - .inDaylightTime(gc.getTime()))); - Date date = new Date(gc.getTime().getTime() + 1000); - assertTrue("Returned incorrect daylight value4", zone - .inDaylightTime(date)); - gc.set(1999, Calendar.OCTOBER, 31, 1, 0, 0); - assertTrue("Returned incorrect daylight value5", !(zone - .inDaylightTime(gc.getTime()))); - date = new Date(gc.getTime().getTime() - 1000); - assertTrue("Returned incorrect daylight value6", zone - .inDaylightTime(date)); - - assertTrue("Returned incorrect daylight value7", !zone - .inDaylightTime(new Date(891752400000L + 7200000 - 1))); - assertTrue("Returned incorrect daylight value8", zone - .inDaylightTime(new Date(891752400000L + 7200000))); - assertTrue("Returned incorrect daylight value9", zone - .inDaylightTime(new Date(909288000000L + 7200000 - 1))); - assertTrue("Returned incorrect daylight value10", !zone - .inDaylightTime(new Date(909288000000L + 7200000))); - } - - /** - * java.util.SimpleTimeZone#setDSTSavings(int) - */ - public void test_setDSTSavingsI() { - // Test for method void java.util.SimpleTimeZone.setDSTSavings(int) - SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ"); - st.setStartRule(0, 1, 1, 1); - st.setEndRule(11, 1, 1, 1); - st.setDSTSavings(1); - assertEquals(1, st.getDSTSavings()); - try { - st.setDSTSavings(0); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - st.setDSTSavings(-1); - fail(); - } catch (IllegalArgumentException expected) { - } - } - - /** - * java.util.SimpleTimeZone#setEndRule(int, int, int) - */ - public void test_setEndRuleIII() { - SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ"); - st.setStartRule(Calendar.NOVEMBER, 1, 0); - st.setEndRule(Calendar.NOVEMBER, 20, 0); - assertTrue("StartRule improperly set1", st.useDaylightTime()); - assertTrue("StartRule improperly set2", st.inDaylightTime( - new GregorianCalendar(1998, Calendar.NOVEMBER, - 13).getTime())); - assertTrue("StartRule improperly set3", !(st - .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER, - 13).getTime()))); - - try { - st.setEndRule(13, 20, 0); - fail("IllegalArgumentException is not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - - try { - st.setEndRule(1, 32, 0); - fail("IllegalArgumentException is not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - - try { - st.setEndRule(1, 30, 10); - fail("IllegalArgumentException is not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - } - - /** - * java.util.SimpleTimeZone#setEndRule(int, int, int, int) - */ - public void test_setEndRuleIIII() { - // Test for method void java.util.SimpleTimeZone.setEndRule(int, int, - // int, int) - SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ"); - // Spec indicates that both end and start must be set or result is - // undefined - st.setStartRule(Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0); - st.setEndRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, 0); - assertTrue("StartRule improperly set1", st.useDaylightTime()); - assertTrue("StartRule improperly set2", st - .inDaylightTime(new GregorianCalendar(1998, Calendar.NOVEMBER, - 13).getTime())); - assertTrue("StartRule improperly set3", !(st - .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER, - 13).getTime()))); - - try { - st.setEndRule(12, -1, Calendar.SUNDAY, 0); - fail("IllegalArgumentException is not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - - try { - st.setEndRule(Calendar.NOVEMBER, 10, Calendar.SUNDAY, 0); - fail("IllegalArgumentException is not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - - try { - st.setEndRule(Calendar.NOVEMBER, -1, 8, 0); - fail("IllegalArgumentException is not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - - try { - st.setEndRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, -10); - fail("IllegalArgumentException is not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - } - - /** - * java.util.SimpleTimeZone#setEndRule(int, int, int, int, boolean) - */ - public void test_setEndRuleIIIIZ() { - // Test for method void java.util.SimpleTimeZone.setEndRule(int, int, - // int, int, boolean) - SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ"); - // Spec indicates that both end and start must be set or result is - // undefined - st.setStartRule(Calendar.NOVEMBER, 8, Calendar.SUNDAY, 1, false); - st.setEndRule(Calendar.NOVEMBER, 15, Calendar.SUNDAY, 1, true); - assertTrue("StartRule improperly set1", st.useDaylightTime()); - assertTrue("StartRule improperly set2", st - .inDaylightTime((new GregorianCalendar(1999, Calendar.NOVEMBER, - 7, 12, 0).getTime()))); - assertTrue("StartRule improperly set3", st - .inDaylightTime((new GregorianCalendar(1999, Calendar.NOVEMBER, - 20, 12, 0).getTime()))); - assertTrue("StartRule improperly set4", !(st - .inDaylightTime(new GregorianCalendar(1999, Calendar.NOVEMBER, - 6, 12, 0).getTime()))); - assertTrue("StartRule improperly set5", !(st - .inDaylightTime(new GregorianCalendar(1999, Calendar.NOVEMBER, - 21, 12, 0).getTime()))); - - try { - st.setEndRule(20, 15, Calendar.SUNDAY, 1, true); - fail("IllegalArgumentException is not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - - try { - st.setEndRule(Calendar.NOVEMBER, 35, Calendar.SUNDAY, 1, true); - fail("IllegalArgumentException is not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - - try { - st.setEndRule(Calendar.NOVEMBER, 15, 12, 1, true); - fail("IllegalArgumentException is not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - - try { - st.setEndRule(Calendar.NOVEMBER, 15, Calendar.SUNDAY, -1, true); - fail("IllegalArgumentException is not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - } - - /** - * java.util.SimpleTimeZone#setRawOffset(int) - */ - public void test_setRawOffsetI() { - // Test for method void java.util.SimpleTimeZone.setRawOffset(int) - - st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST"); - int off = st1.getRawOffset(); - st1.setRawOffset(1000); - boolean val = st1.getRawOffset() == 1000; - st1.setRawOffset(off); - assertTrue("Incorrect offset set", val); - } - - /** - * java.util.SimpleTimeZone#setStartRule(int, int, int) - */ - public void test_setStartRuleIII() { - // Test for method void java.util.SimpleTimeZone.setStartRule(int, int, - // int) - SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ"); - // Spec indicates that both end and start must be set or result is - // undefined - st.setStartRule(Calendar.NOVEMBER, 1, 1); - st.setEndRule(Calendar.DECEMBER, 1, 1); - assertTrue("StartRule improperly set", st.useDaylightTime()); - assertTrue("StartRule improperly set", st - .inDaylightTime((new GregorianCalendar(1998, Calendar.NOVEMBER, - 13).getTime()))); - assertTrue("StartRule improperly set", !(st - .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER, - 13).getTime()))); - - try { - st.setStartRule(13, 20, 0); - fail("IllegalArgumentException is not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - - try { - st.setStartRule(1, 32, 0); - fail("IllegalArgumentException is not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - - try { - st.setStartRule(1, 30, 10); - fail("IllegalArgumentException is not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - } - - /** - * java.util.SimpleTimeZone#setStartRule(int, int, int, int) - */ - public void test_setStartRuleIIII() { - // Test for method void java.util.SimpleTimeZone.setStartRule(int, int, - // int, int) - SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ"); - // Spec indicates that both end and start must be set or result is - // undefined - st.setStartRule(Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0); - st.setEndRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, 0); - assertTrue("StartRule improperly set1", st.useDaylightTime()); - assertTrue("StartRule improperly set2", st - .inDaylightTime((new GregorianCalendar(1998, Calendar.NOVEMBER, - 13).getTime()))); - assertTrue("StartRule improperly set3", !(st - .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER, - 13).getTime()))); - - try { - st.setStartRule(12, -1, Calendar.SUNDAY, 0); - fail("IllegalArgumentException is not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - - try { - st.setStartRule(Calendar.NOVEMBER, 10, Calendar.SUNDAY, 0); - fail("IllegalArgumentException is not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - - try { - st.setStartRule(Calendar.NOVEMBER, -1, 8, 0); - fail("IllegalArgumentException is not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - - try { - st.setStartRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, -10); - fail("IllegalArgumentException is not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - } - - /** - * java.util.SimpleTimeZone#setStartRule(int, int, int, int, boolean) - */ - public void test_setStartRuleIIIIZ() { - TimeZone.setDefault(TimeZone.getTimeZone("GMT")); - // Test for method void java.util.SimpleTimeZone.setStartRule(int, int, - // int, int, boolean) - SimpleTimeZone st = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST"); - // Spec indicates that both end and start must be set or result is - // undefined - st.setStartRule(Calendar.NOVEMBER, 1, Calendar.SUNDAY, 1, true); - st.setEndRule(Calendar.NOVEMBER, 15, Calendar.SUNDAY, 1, false); - assertTrue("StartRule improperly set1", st.useDaylightTime()); - assertTrue("StartRule improperly set2", st - .inDaylightTime((new GregorianCalendar(1999, Calendar.NOVEMBER, - 7, 12, 0).getTime()))); - assertTrue("StartRule improperly set3", st - .inDaylightTime((new GregorianCalendar(1999, Calendar.NOVEMBER, - 13, 12, 0).getTime()))); - assertTrue("StartRule improperly set4", !(st - .inDaylightTime(new GregorianCalendar(1999, Calendar.NOVEMBER, - 6, 12, 0).getTime()))); - assertTrue("StartRule improperly set5", !(st - .inDaylightTime(new GregorianCalendar(1999, Calendar.NOVEMBER, - 14, 12, 0).getTime()))); - - try { - st.setStartRule(20, 15, Calendar.SUNDAY, 1, true); - fail("IllegalArgumentException is not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - - try { - st.setStartRule(Calendar.NOVEMBER, 35, Calendar.SUNDAY, 1, true); - fail("IllegalArgumentException is not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - - try { - st.setStartRule(Calendar.NOVEMBER, 15, 12, 1, true); - fail("IllegalArgumentException is not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - - try { - st.setStartRule(Calendar.NOVEMBER, 15, Calendar.SUNDAY, -1, true); - fail("IllegalArgumentException is not thrown."); - } catch(IllegalArgumentException iae) { - //expected - } - } - - /** - * java.util.SimpleTimeZone#setStartYear(int) - */ - public void test_setStartYearI() { - // Test for method void java.util.SimpleTimeZone.setStartYear(int) - SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ"); - st.setStartRule(Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0); - st.setEndRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, 0); - st.setStartYear(1999); - assertTrue("set year improperly set1", !(st - .inDaylightTime(new GregorianCalendar(1999, Calendar.JULY, 12) - .getTime()))); - assertTrue("set year improperly set2", !(st - .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER, - 13).getTime()))); - assertTrue("set year improperly set3", (st - .inDaylightTime(new GregorianCalendar(1999, Calendar.NOVEMBER, - 13).getTime()))); - } - - /** - * java.util.SimpleTimeZone#toString() - */ - public void test_toString() { - // Test for method java.lang.String java.util.SimpleTimeZone.toString() - String string = TimeZone.getTimeZone("EST").toString(); - assertNotNull("toString() returned null", string); - assertTrue("toString() is empty", string.length() != 0); - } - - /** - * java.util.SimpleTimeZone#useDaylightTime() - */ - public void test_useDaylightTime() { - // Test for method boolean java.util.SimpleTimeZone.useDaylightTime() - SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ"); - assertTrue("useDaylightTime returned incorrect value", !st - .useDaylightTime()); - // Spec indicates that both end and start must be set or result is - // undefined - st.setStartRule(Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0); - st.setEndRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, 0); - assertTrue("useDaylightTime returned incorrect value", st - .useDaylightTime()); - } - - public void test_getOffsetJ() { - Calendar cal = Calendar.getInstance(); - cal.set(1998, Calendar.NOVEMBER, 11, 0, 0); - st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST"); - - assertTrue("Incorrect offset returned", st1.getOffset(cal.getTimeInMillis()) == - -(5 * 60 * 60 * 1000)); - - st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST"); - cal.set(1998, Calendar.JUNE, 11, 0, 0); - assertEquals("Incorrect offset returned", -(5 * 60 * 60 * 1000), st1 - .getOffset(cal.getTimeInMillis())); - - // Regression for HARMONY-5459 - st1 = new SimpleTimeZone(TimeZone.getDefault().getRawOffset(), TimeZone.getDefault().getID()); - int fourHours = 4*60*60*1000; - st1.setRawOffset(fourHours); - cal.set(2099, 01, 1, 0, 0); - - assertEquals(fourHours, st1.getOffset(cal.getTimeInMillis())); - - } - - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/util/StackTest.java b/luni/src/test/java/tests/api/java/util/StackTest.java deleted file mode 100644 index 465df13..0000000 --- a/luni/src/test/java/tests/api/java/util/StackTest.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.EmptyStackException; -import java.util.Stack; - -public class StackTest extends junit.framework.TestCase { - - Stack s; - - /** - * java.util.Stack#Stack() - */ - public void test_Constructor() { - // Test for method java.util.Stack() - assertEquals("Stack creation failed", 0, s.size()); - } - - /** - * java.util.Stack#empty() - */ - public void test_empty() { - // Test for method boolean java.util.Stack.empty() - assertTrue("New stack answers non-empty", s.empty()); - s.push("blah"); - assertTrue("Stack should not be empty but answers empty", !s.empty()); - s.pop(); - assertTrue("Stack should be empty but answers non-empty", s.empty()); - s.push(null); - assertTrue("Stack with null should not be empty but answers empty", !s - .empty()); - } - - /** - * java.util.Stack#peek() - */ - public void test_peek() { - // Test for method java.lang.Object java.util.Stack.peek() - String item1 = "Ichi"; - String item2 = "Ni"; - String item3 = "San"; - s.push(item1); - assertTrue("Peek did not return top item when it was the only item", s - .peek() == item1); - s.push(item2); - s.push(item3); - assertTrue("Peek did not return top item amoung many other items", s - .peek() == item3); - s.pop(); - assertTrue("Peek did not return top item after a pop", s.pop() == item2); - s.push(null); - assertNull("Peek did not return top item (wanted: null)", - s.peek()); - s.pop(); - s.pop(); - try { - s.pop(); - fail("EmptyStackException expected"); - } catch (EmptyStackException e) { - //expected - } - } - - /** - * java.util.Stack#pop() - */ - public void test_pop() { - // Test for method java.lang.Object java.util.Stack.pop() - String item1 = "Ichi"; - String item2 = "Ni"; - Object lastPopped; - s.push(item1); - s.push(item2); - - try { - lastPopped = s.pop(); - assertTrue("a) Pop did not return top item", lastPopped == item2); - } catch (EmptyStackException e) { - fail( - "a) Pop threw EmptyStackException when stack should not have been empty"); - } - - try { - lastPopped = s.pop(); - assertTrue("b) Pop did not return top item", lastPopped == item1); - } catch (EmptyStackException e) { - fail( - "b) Pop threw EmptyStackException when stack should not have been empty"); - } - - s.push(null); - try { - lastPopped = s.pop(); - assertNull("c) Pop did not return top item", lastPopped); - } catch (EmptyStackException e) { - fail( - "c) Pop threw EmptyStackException when stack should not have been empty"); - } - - try { - lastPopped = s.pop(); - fail( - "d) Pop did not throw EmptyStackException when stack should have been empty"); - } catch (EmptyStackException e) { - return; - } - - } - - /** - * java.util.Stack#push(java.lang.Object) - */ - public void test_pushLjava_lang_Object() { - Object [] array = {new Integer(0), new Object(), - new Float(0), new String()}; - - Stack<Object> stack = new Stack<Object>(); - for(int i = 0; i < array.length; i++) { - stack.push(array[i]); - } - for(int i = 0; i < array.length; i++) { - assertEquals(array.length - i, stack.search(array[i])); - } - } - - /** - * java.util.Stack#search(java.lang.Object) - */ - public void test_searchLjava_lang_Object() { - // Test for method int java.util.Stack.search(java.lang.Object) - String item1 = "Ichi"; - String item2 = "Ni"; - String item3 = "San"; - s.push(item1); - s.push(item2); - s.push(item3); - assertEquals("Search returned incorrect value for equivalent object", 3, s - .search(item1)); - assertEquals("Search returned incorrect value for equal object", 3, s - .search("Ichi")); - s.pop(); - assertEquals("Search returned incorrect value for equivalent object at top of stack", - 1, s.search(item2)); - assertEquals("Search returned incorrect value for equal object at top of stack", - 1, s.search("Ni")); - s.push(null); - assertEquals("Search returned incorrect value for search for null at top of stack", - 1, s.search(null)); - s.push("Shi"); - assertEquals("Search returned incorrect value for search for null", 2, s - .search(null)); - s.pop(); - s.pop(); - assertEquals("Search returned incorrect value for search for null--wanted -1", - -1, s.search(null)); - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - s = new Stack(); - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/util/StringTokenizerTest.java b/luni/src/test/java/tests/api/java/util/StringTokenizerTest.java deleted file mode 100644 index 809ed99..0000000 --- a/luni/src/test/java/tests/api/java/util/StringTokenizerTest.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.NoSuchElementException; -import java.util.StringTokenizer; - -public class StringTokenizerTest extends junit.framework.TestCase { - - /** - * java.util.StringTokenizer#StringTokenizer(java.lang.String) - */ - public void test_ConstructorLjava_lang_String() { - // Test for method java.util.StringTokenizer(java.lang.String) - try { - new StringTokenizer(null); - fail("NullPointerException is not thrown."); - } catch(NullPointerException npe) { - //expected - } - } - - /** - * java.util.StringTokenizer#StringTokenizer(java.lang.String, - * java.lang.String) - */ - public void test_ConstructorLjava_lang_StringLjava_lang_String() { - // Test for method java.util.StringTokenizer(java.lang.String, - // java.lang.String) - StringTokenizer st = new StringTokenizer("This:is:a:test:String", ":"); - assertTrue("Created incorrect tokenizer", st.countTokens() == 5 - && (st.nextElement().equals("This"))); - st = new StringTokenizer("This:is:a:test:String", null); - - try { - new StringTokenizer(null, ":"); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.StringTokenizer#StringTokenizer(java.lang.String, - * java.lang.String, boolean) - */ - public void test_ConstructorLjava_lang_StringLjava_lang_StringZ() { - // Test for method java.util.StringTokenizer(java.lang.String, - // java.lang.String, boolean) - StringTokenizer st = new StringTokenizer("This:is:a:test:String", ":", - true); - st.nextElement(); - assertTrue("Created incorrect tokenizer", st.countTokens() == 8 - && (st.nextElement().equals(":"))); - st = new StringTokenizer("This:is:a:test:String", null, true); - st = new StringTokenizer("This:is:a:test:String", null, false); - - try { - new StringTokenizer(null, ":", true); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.StringTokenizer#countTokens() - */ - public void test_countTokens() { - // Test for method int java.util.StringTokenizer.countTokens() - StringTokenizer st = new StringTokenizer("This is a test String"); - - assertEquals("Incorrect token count returned", 5, st.countTokens()); - } - - /** - * java.util.StringTokenizer#hasMoreElements() - */ - public void test_hasMoreElements() { - // Test for method boolean java.util.StringTokenizer.hasMoreElements() - - StringTokenizer st = new StringTokenizer("This is a test String"); - st.nextElement(); - assertTrue("hasMoreElements returned incorrect value", st - .hasMoreElements()); - st.nextElement(); - st.nextElement(); - st.nextElement(); - st.nextElement(); - assertTrue("hasMoreElements returned incorrect value", !st - .hasMoreElements()); - } - - /** - * java.util.StringTokenizer#hasMoreTokens() - */ - public void test_hasMoreTokens() { - // Test for method boolean java.util.StringTokenizer.hasMoreTokens() - StringTokenizer st = new StringTokenizer("This is a test String"); - for (int counter = 0; counter < 5; counter++) { - assertTrue( - "StringTokenizer incorrectly reports it has no more tokens", - st.hasMoreTokens()); - st.nextToken(); - } - assertTrue("StringTokenizer incorrectly reports it has more tokens", - !st.hasMoreTokens()); - } - - /** - * java.util.StringTokenizer#nextElement() - */ - public void test_nextElement() { - // Test for method java.lang.Object - // java.util.StringTokenizer.nextElement() - StringTokenizer st = new StringTokenizer("This is a test String"); - assertEquals("nextElement returned incorrect value", "This", ((String) st - .nextElement())); - assertEquals("nextElement returned incorrect value", "is", ((String) st - .nextElement())); - assertEquals("nextElement returned incorrect value", "a", ((String) st - .nextElement())); - assertEquals("nextElement returned incorrect value", "test", ((String) st - .nextElement())); - assertEquals("nextElement returned incorrect value", "String", ((String) st - .nextElement())); - try { - st.nextElement(); - fail( - "nextElement failed to throw a NoSuchElementException when it should have been out of elements"); - } catch (NoSuchElementException e) { - return; - } - } - - /** - * java.util.StringTokenizer#nextToken() - */ - public void test_nextToken() { - // Test for method java.lang.String - // java.util.StringTokenizer.nextToken() - StringTokenizer st = new StringTokenizer("This is a test String"); - assertEquals("nextToken returned incorrect value", - "This", st.nextToken()); - assertEquals("nextToken returned incorrect value", - "is", st.nextToken()); - assertEquals("nextToken returned incorrect value", - "a", st.nextToken()); - assertEquals("nextToken returned incorrect value", - "test", st.nextToken()); - assertEquals("nextToken returned incorrect value", - "String", st.nextToken()); - try { - st.nextToken(); - fail( - "nextToken failed to throw a NoSuchElementException when it should have been out of elements"); - } catch (NoSuchElementException e) { - return; - } - } - - /** - * java.util.StringTokenizer#nextToken(java.lang.String) - */ - public void test_nextTokenLjava_lang_String() { - // Test for method java.lang.String - // java.util.StringTokenizer.nextToken(java.lang.String) - StringTokenizer st = new StringTokenizer("This is a test String"); - assertEquals("nextToken(String) returned incorrect value with normal token String", - "This", st.nextToken(" ")); - assertEquals("nextToken(String) returned incorrect value with custom token String", - " is a ", st.nextToken("tr")); - assertEquals("calling nextToken() did not use the new default delimiter list", - "es", st.nextToken()); - st = new StringTokenizer("This:is:a:test:String", " "); - assertTrue(st.nextToken(":").equals("This")); - assertTrue(st.nextToken(":").equals("is")); - assertTrue(st.nextToken(":").equals("a")); - assertTrue(st.nextToken(":").equals("test")); - assertTrue(st.nextToken(":").equals("String")); - - try { - st.nextToken(":"); - fail("NoSuchElementException expected"); - } catch (NoSuchElementException e) { - //expected - } - - try { - st.nextToken(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/util/TimerTaskTest.java b/luni/src/test/java/tests/api/java/util/TimerTaskTest.java deleted file mode 100644 index 97ff8ea..0000000 --- a/luni/src/test/java/tests/api/java/util/TimerTaskTest.java +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.Timer; -import java.util.TimerTask; - -public class TimerTaskTest extends junit.framework.TestCase { - /** - * Warning: These tests have the possibility to leave a VM hanging if the - * Timer is not cancelled. - */ - class TimerTestTask extends TimerTask { - - private final Object sync = new Object(); - private final Object start = new Object(); - - private int wasRun = 0; - - // Set this to true to see normal tests fail (or hang possibly) - // The default is false and needs to be set by some tests - private boolean sleepInRun = false; - - public void run() { - synchronized (this) { - wasRun++; - } - synchronized (start) { - start.notify(); - } - if (sleepInRun) { - - try { - Thread.sleep(200); - } catch (InterruptedException e) { - } - } - synchronized (sync) { - sync.notify(); - } - } - - public synchronized int wasRun() { - return wasRun; - } - - public void sleepInRun(boolean value) { - sleepInRun = value; - } - } - - /** - * java.util.TimerTask#TimerTask() - */ - public void test_Constructor() { - // Ensure the constructor does not fail - new TimerTestTask(); - } - - /** - * java.util.TimerTask#cancel() - */ - public void test_cancel() { - Timer t = null; - try { - // Ensure cancel returns false if never scheduled - TimerTestTask testTask = new TimerTestTask(); - assertTrue("Unsheduled tasks should return false for cancel()", - !testTask.cancel()); - - // Ensure cancelled task never runs - t = new Timer(); - testTask = new TimerTestTask(); - t.schedule(testTask, 500); - assertTrue("TimerTask should not have run yet", testTask.cancel()); - t.cancel(); - - // Ensure cancelling a task which has already run returns true - t = new Timer(); - testTask = new TimerTestTask(); - t.schedule(testTask, 50); - while (testTask.wasRun() == 0) { - try { - Thread.sleep(150); - } catch (InterruptedException e) { - } - } - assertFalse( - "TimerTask.cancel() should return false if task has run", - testTask.cancel()); - assertFalse( - "TimerTask.cancel() should return false if called a second time", - testTask.cancel()); - t.cancel(); - - // Ensure cancelling a repeated execution task which has never run - // returns true - t = new Timer(); - testTask = new TimerTestTask(); - t.schedule(testTask, 500, 500); // should never run - assertTrue( - "TimerTask.cancel() should return true if sheduled for repeated execution even if not run", - testTask.cancel()); - t.cancel(); - - // Ensure cancelling a repeated execution task which HAS run returns - // true - t = new Timer(); - testTask = new TimerTestTask(); - t.schedule(testTask, 50, 50); - while (testTask.wasRun() == 0) { - try { - Thread.sleep(100); - } catch (InterruptedException e) { - } - } - assertTrue( - "TimerTask.cancel() should return true if sheduled for repeated execution and run", - testTask.cancel()); - t.cancel(); - - // Ensure calling cancel a second returns false - t = new Timer(); - testTask = new TimerTestTask(); - t.schedule(testTask, 5000); // Should never run - assertTrue( - "TimerTask.cancel() should return true if task has never run", - testTask.cancel()); - assertFalse( - "TimerTask.cancel() should return false if called a second time", - testTask.cancel()); - t.cancel(); - - // Ensure cancelling a task won't cause deadlock - t = new Timer(); - testTask = new TimerTestTask(); - testTask.sleepInRun(true); - synchronized (testTask.start) { - t.schedule(testTask, 0); - try { - testTask.start.wait(); - Thread.sleep(50); - } catch (InterruptedException e) { - } - } - assertFalse("TimerTask should have been cancelled", testTask - .cancel()); - t.cancel(); - } finally { - if (t != null) - t.cancel(); - } - } - - /** - * java.util.TimerTask#scheduledExecutionTime() - */ - public void test_scheduledExecutionTime() { - Timer t = null; - try { - // Ensure scheduledExecutionTime is roughly right - t = new Timer(); - TimerTestTask testTask = new TimerTestTask(); - t.schedule(testTask, 100); - long time = System.currentTimeMillis() + 100; - synchronized (testTask.sync) { - try { - testTask.sync.wait(500); - } catch (InterruptedException e) { - } - } - long scheduledExecutionTime = testTask.scheduledExecutionTime(); - assertTrue(scheduledExecutionTime <= time); - t.cancel(); - - // Ensure scheduledExecutionTime is the last scheduled time - t = new Timer(); - testTask = new TimerTestTask(); - t.schedule(testTask, 100, 500); - long estNow = System.currentTimeMillis() + 100; - // Will wake in 100, and every 500 run again - // We want to try to get it after it's run at least once but not - // twice - synchronized (testTask.sync) { - try { - testTask.sync.wait(500); - } catch (InterruptedException e) { - } - } - scheduledExecutionTime = testTask.scheduledExecutionTime(); - assertTrue(scheduledExecutionTime <= estNow); - t.cancel(); - } finally { - if (t != null) - t.cancel(); - } - - } - - /** - * java.util.TimerTask#run() - */ - public void test_run() { - Timer t = null; - try { - // Ensure a new task is never run - TimerTestTask testTask = new TimerTestTask(); - try { - Thread.sleep(200); - } catch (InterruptedException e) { - } - assertEquals("TimerTask.run() method should not have been called", - 0, testTask.wasRun()); - - // Ensure a task is run - t = new Timer(); - testTask = new TimerTestTask(); - t.schedule(testTask, 200); - while(testTask.wasRun() < 1) { - try { - Thread.sleep(400); - } catch (InterruptedException e) { - } - } - assertFalse(testTask.cancel()); - t.cancel(); - } finally { - if (t != null) - t.cancel(); - } - - } -} diff --git a/luni/src/test/java/tests/api/java/util/TimerTest.java b/luni/src/test/java/tests/api/java/util/TimerTest.java deleted file mode 100644 index 739c018..0000000 --- a/luni/src/test/java/tests/api/java/util/TimerTest.java +++ /dev/null @@ -1,986 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.lang.Thread.UncaughtExceptionHandler; -import java.util.Date; -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.atomic.AtomicReference; -import junit.framework.TestCase; - -public class TimerTest extends TestCase { - - int timerCounter = 0; - - private final Object sync = new Object(); - - /** - * Warning: These tests have the possibility to leave a VM hanging if the - * Timer is not cancelled. - */ - class TimerTestTask extends TimerTask { - int wasRun = 0; - - // Should we sleep for 200 ms each run()? - boolean sleepInRun = false; - - // Should we increment the timerCounter? - boolean incrementCount = false; - - // Should we terminate the timer at a specific timerCounter? - int terminateCount = -1; - - // The timer we belong to - Timer timer = null; - - public TimerTestTask() { - } - - public TimerTestTask(Timer t) { - timer = t; - } - - public void run() { - synchronized (this) { - wasRun++; - } - if (incrementCount) { - timerCounter++; - } - if (terminateCount == timerCounter && timer != null) { - timer.cancel(); - } - if (sleepInRun) { - try { - Thread.sleep(200); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } - synchronized (sync) { - sync.notify(); - } - } - - public synchronized int wasRun() { - return wasRun; - } - - public void sleepInRun(boolean sleepInRun) { - this.sleepInRun = sleepInRun; - } - - public void incrementCount(boolean incrementCount) { - this.incrementCount = incrementCount; - } - - public void terminateCount(int terminateCount) { - this.terminateCount = terminateCount; - } - } - - private void awaitRun(TimerTestTask task) throws Exception { - while (task.wasRun() == 0) { - Thread.sleep(150); - } - } - - /** - * java.util.Timer#Timer(boolean) - */ - public void test_ConstructorZ() throws Exception { - Timer t = null; - try { - // Ensure a task is run - t = new Timer(true); - TimerTestTask testTask = new TimerTestTask(); - t.schedule(testTask, 200); - awaitRun(testTask); - t.cancel(); - } finally { - if (t != null) - t.cancel(); - } - - } - - /** - * java.util.Timer#Timer() - */ - public void test_Constructor() throws Exception { - Timer t = null; - try { - // Ensure a task is run - t = new Timer(); - TimerTestTask testTask = new TimerTestTask(); - t.schedule(testTask, 200); - awaitRun(testTask); - t.cancel(); - } finally { - if (t != null) - t.cancel(); - } - - } - - /** - * java.util.Timer#Timer(String, boolean) - */ - public void test_ConstructorSZ() throws Exception { - Timer t = null; - try { - // Ensure a task is run - t = new Timer("test_ConstructorSZThread", true); - TimerTestTask testTask = new TimerTestTask(); - t.schedule(testTask, 200); - awaitRun(testTask); - t.cancel(); - } finally { - if (t != null) - t.cancel(); - } - - try { - new Timer(null, true); - fail(); - } catch (NullPointerException expected) { - } - - try { - new Timer(null, false); - fail(); - } catch (NullPointerException expected) { - } - } - - /** - * java.util.Timer#Timer(String) - */ - public void test_ConstructorS() throws Exception { - Timer t = null; - try { - // Ensure a task is run - t = new Timer("test_ConstructorSThread"); - TimerTestTask testTask = new TimerTestTask(); - t.schedule(testTask, 200); - awaitRun(testTask); - t.cancel(); - } finally { - if (t != null) - t.cancel(); - } - - try { - new Timer(null); - fail(); - } catch (NullPointerException expected) { - } - } - - /** - * java.util.Timer#cancel() - */ - public void test_cancel() throws Exception { - Timer t = null; - try { - // Ensure a task throws an IllegalStateException after cancelled - t = new Timer(); - TimerTestTask testTask = new TimerTestTask(); - t.cancel(); - try { - t.schedule(testTask, 100, 200); - fail("Scheduling a task after Timer.cancel() should throw exception"); - } catch (IllegalStateException expected) { - } - - // Ensure a task is run but not after cancel - t = new Timer(); - testTask = new TimerTestTask(); - t.schedule(testTask, 100, 500); - awaitRun(testTask); - t.cancel(); - synchronized (sync) { - sync.wait(500); - } - assertEquals("TimerTask.run() method should not have been called after cancel", - 1, testTask.wasRun()); - - // Ensure you can call cancel more than once - t = new Timer(); - testTask = new TimerTestTask(); - t.schedule(testTask, 100, 500); - awaitRun(testTask); - t.cancel(); - t.cancel(); - t.cancel(); - synchronized (sync) { - sync.wait(500); - } - assertEquals("TimerTask.run() method should not have been called after cancel", - 1, testTask.wasRun()); - - // Ensure that a call to cancel from within a timer ensures no more - // run - t = new Timer(); - testTask = new TimerTestTask(t); - testTask.incrementCount(true); - testTask.terminateCount(5); // Terminate after 5 runs - t.schedule(testTask, 100, 100); - synchronized (sync) { - sync.wait(200); - assertEquals(1, testTask.wasRun()); - sync.wait(200); - assertEquals(2, testTask.wasRun()); - sync.wait(200); - assertEquals(3, testTask.wasRun()); - sync.wait(200); - assertEquals(4, testTask.wasRun()); - sync.wait(200); - assertEquals(5, testTask.wasRun()); - sync.wait(200); - assertEquals(5, testTask.wasRun()); - } - t.cancel(); - Thread.sleep(200); - } finally { - if (t != null) - t.cancel(); - } - - } - - /** - * java.util.Timer#purge() - */ - public void test_purge() throws Exception { - Timer t = null; - try { - t = new Timer(); - assertEquals(0, t.purge()); - - TimerTestTask[] tasks = new TimerTestTask[100]; - int[] delayTime = { 50, 80, 20, 70, 40, 10, 90, 30, 60 }; - - int j = 0; - for (int i = 0; i < 100; i++) { - tasks[i] = new TimerTestTask(); - t.schedule(tasks[i], delayTime[j++], 200); - if (j == 9) { - j = 0; - } - } - - for (int i = 0; i < 50; i++) { - tasks[i].cancel(); - } - - assertTrue(t.purge() <= 50); - assertEquals(0, t.purge()); - } finally { - if (t != null) { - t.cancel(); - } - } - } - - /** - * java.util.Timer#schedule(java.util.TimerTask, java.util.Date) - */ - public void test_scheduleLjava_util_TimerTaskLjava_util_Date() throws Exception { - Timer t = null; - try { - // Ensure a Timer throws an IllegalStateException after cancelled - t = new Timer(); - TimerTestTask testTask = new TimerTestTask(); - Date d = new Date(System.currentTimeMillis() + 100); - t.cancel(); - try { - t.schedule(testTask, d); - fail("Scheduling a task after Timer.cancel() should throw exception"); - } catch (IllegalStateException expected) { - } - - // Ensure a Timer throws an IllegalStateException if task already - // cancelled - t = new Timer(); - testTask = new TimerTestTask(); - d = new Date(System.currentTimeMillis() + 100); - testTask.cancel(); - try { - t.schedule(testTask, d); - fail("Scheduling a task after cancelling it should throw exception"); - } catch (IllegalStateException expected) { - } - t.cancel(); - - // Ensure a Timer throws an IllegalArgumentException if delay is - // negative - t = new Timer(); - testTask = new TimerTestTask(); - d = new Date(-100); - try { - t.schedule(testTask, d); - fail("Scheduling a task with negative date should throw IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - t.cancel(); - - // Ensure a Timer throws a NullPointerException if the task is null - t = new Timer(); - d = new Date(System.currentTimeMillis() + 100); - try { - t.schedule(null, d); - fail("Scheduling a null task should throw NullPointerException"); - } catch (NullPointerException expected) { - } - t.cancel(); - - // Ensure a Timer throws a NullPointerException if the date is null - t = new Timer(); - testTask = new TimerTestTask(); - try { - t.schedule(testTask, null); - fail("Scheduling a null date should throw NullPointerException"); - } catch (NullPointerException expected) { - } - t.cancel(); - - // Ensure proper sequence of exceptions - t = new Timer(); - d = new Date(-100); - try { - t.schedule(null, d); - fail("Scheduling a null task with negative date should throw IllegalArgumentException first"); - } catch (IllegalArgumentException expected) { - } - t.cancel(); - - // Ensure a task is run - t = new Timer(); - testTask = new TimerTestTask(); - d = new Date(System.currentTimeMillis() + 200); - t.schedule(testTask, d); - awaitRun(testTask); - t.cancel(); - - // Ensure multiple tasks are run - t = new Timer(); - testTask = new TimerTestTask(); - testTask.incrementCount(true); - d = new Date(System.currentTimeMillis() + 100); - t.schedule(testTask, d); - testTask = new TimerTestTask(); - testTask.incrementCount(true); - d = new Date(System.currentTimeMillis() + 150); - t.schedule(testTask, d); - testTask = new TimerTestTask(); - testTask.incrementCount(true); - d = new Date(System.currentTimeMillis() + 70); - t.schedule(testTask, d); - testTask = new TimerTestTask(); - testTask.incrementCount(true); - d = new Date(System.currentTimeMillis() + 10); - t.schedule(testTask, d); - Thread.sleep(400); - assertTrue("Multiple tasks should have incremented counter 4 times not " - + timerCounter, timerCounter == 4); - t.cancel(); - } finally { - if (t != null) - t.cancel(); - } - } - - /** - * java.util.Timer#schedule(java.util.TimerTask, long) - */ - public void test_scheduleLjava_util_TimerTaskJ() throws Exception { - Timer t = null; - try { - // Ensure a Timer throws an IllegalStateException after cancelled - t = new Timer(); - TimerTestTask testTask = new TimerTestTask(); - t.cancel(); - try { - t.schedule(testTask, 100); - fail("Scheduling a task after Timer.cancel() should throw exception"); - } catch (IllegalStateException expected) { - } - - // Ensure a Timer throws an IllegalStateException if task already - // cancelled - t = new Timer(); - testTask = new TimerTestTask(); - testTask.cancel(); - try { - t.schedule(testTask, 100); - fail("Scheduling a task after cancelling it should throw exception"); - } catch (IllegalStateException expected) { - } - t.cancel(); - - // Ensure a Timer throws an IllegalArgumentException if delay is - // negative - t = new Timer(); - testTask = new TimerTestTask(); - try { - t.schedule(testTask, -100); - fail("Scheduling a task with negative delay should throw IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - t.cancel(); - - // Ensure a Timer throws a NullPointerException if the task is null - t = new Timer(); - try { - t.schedule(null, 10); - fail("Scheduling a null task should throw NullPointerException"); - } catch (NullPointerException expected) { - } - t.cancel(); - - // Ensure proper sequence of exceptions - t = new Timer(); - try { - t.schedule(null, -10); - fail("Scheduling a null task with negative delays should throw IllegalArgumentException first"); - } catch (IllegalArgumentException expected) { - } - t.cancel(); - - // Ensure a task is run - t = new Timer(); - testTask = new TimerTestTask(); - t.schedule(testTask, 200); - awaitRun(testTask); - t.cancel(); - - // Ensure multiple tasks are run - t = new Timer(); - testTask = new TimerTestTask(); - testTask.incrementCount(true); - t.schedule(testTask, 100); - testTask = new TimerTestTask(); - testTask.incrementCount(true); - t.schedule(testTask, 150); - testTask = new TimerTestTask(); - testTask.incrementCount(true); - t.schedule(testTask, 70); - testTask = new TimerTestTask(); - testTask.incrementCount(true); - t.schedule(testTask, 10); - Thread.sleep(400); - assertTrue("Multiple tasks should have incremented counter 4 times not " - + timerCounter, timerCounter == 4); - t.cancel(); - } finally { - if (t != null) - t.cancel(); - } - } - - /** - * java.util.Timer#schedule(java.util.TimerTask, long, long) - */ - public void test_scheduleLjava_util_TimerTaskJJ() throws Exception { - Timer t = null; - try { - // Ensure a Timer throws an IllegalStateException after cancelled - t = new Timer(); - TimerTestTask testTask = new TimerTestTask(); - t.cancel(); - try { - t.schedule(testTask, 100, 100); - fail("Scheduling a task after Timer.cancel() should throw exception"); - } catch (IllegalStateException expected) { - } - - // Ensure a Timer throws an IllegalStateException if task already - // cancelled - t = new Timer(); - testTask = new TimerTestTask(); - testTask.cancel(); - try { - t.schedule(testTask, 100, 100); - fail("Scheduling a task after cancelling it should throw exception"); - } catch (IllegalStateException expected) { - } - t.cancel(); - - // Ensure a Timer throws an IllegalArgumentException if delay is - // negative - t = new Timer(); - testTask = new TimerTestTask(); - try { - t.schedule(testTask, -100, 100); - fail("Scheduling a task with negative delay should throw IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - t.cancel(); - - // Ensure a Timer throws an IllegalArgumentException if period is - // negative - t = new Timer(); - testTask = new TimerTestTask(); - try { - t.schedule(testTask, 100, -100); - fail("Scheduling a task with negative period should throw IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - t.cancel(); - - // Ensure a Timer throws an IllegalArgumentException if period is - // zero - t = new Timer(); - testTask = new TimerTestTask(); - try { - t.schedule(testTask, 100, 0); - fail("Scheduling a task with 0 period should throw IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - t.cancel(); - - // Ensure a Timer throws a NullPointerException if the task is null - t = new Timer(); - try { - t.schedule(null, 10, 10); - fail("Scheduling a null task should throw NullPointerException"); - } catch (NullPointerException expected) { - } - t.cancel(); - - // Ensure proper sequence of exceptions - t = new Timer(); - try { - t.schedule(null, -10, -10); - fail("Scheduling a null task with negative delays should throw IllegalArgumentException first"); - } catch (IllegalArgumentException expected) { - } - t.cancel(); - - // Ensure a task is run at least twice - t = new Timer(); - testTask = new TimerTestTask(); - t.schedule(testTask, 100, 100); - Thread.sleep(400); - assertTrue("TimerTask.run() method should have been called at least twice (" - + testTask.wasRun() + ")", testTask.wasRun() >= 2); - t.cancel(); - - // Ensure multiple tasks are run - t = new Timer(); - testTask = new TimerTestTask(); - testTask.incrementCount(true); - t.schedule(testTask, 100, 100); // at least 9 times - testTask = new TimerTestTask(); - testTask.incrementCount(true); - t.schedule(testTask, 200, 100); // at least 7 times - testTask = new TimerTestTask(); - testTask.incrementCount(true); - t.schedule(testTask, 300, 200); // at least 4 times - testTask = new TimerTestTask(); - testTask.incrementCount(true); - t.schedule(testTask, 100, 200); // at least 4 times - Thread.sleep(1200); // Allowed more room for error - assertTrue("Multiple tasks should have incremented counter 24 times not " - + timerCounter, timerCounter >= 24); - t.cancel(); - } finally { - if (t != null) - t.cancel(); - } - } - - /** - * java.util.Timer#schedule(java.util.TimerTask, java.util.Date, - * long) - */ - public void test_scheduleLjava_util_TimerTaskLjava_util_DateJ() throws Exception { - Timer t = null; - try { - // Ensure a Timer throws an IllegalStateException after cancelled - t = new Timer(); - TimerTestTask testTask = new TimerTestTask(); - Date d = new Date(System.currentTimeMillis() + 100); - t.cancel(); - try { - t.schedule(testTask, d, 100); - fail("Scheduling a task after Timer.cancel() should throw exception"); - } catch (IllegalStateException expected) { - } - - // Ensure a Timer throws an IllegalStateException if task already - // cancelled - t = new Timer(); - d = new Date(System.currentTimeMillis() + 100); - testTask = new TimerTestTask(); - testTask.cancel(); - try { - t.schedule(testTask, d, 100); - fail("Scheduling a task after cancelling it should throw exception"); - } catch (IllegalStateException expected) { - } - t.cancel(); - - // Ensure a Timer throws an IllegalArgumentException if delay is - // negative - t = new Timer(); - d = new Date(-100); - testTask = new TimerTestTask(); - try { - t.schedule(testTask, d, 100); - fail("Scheduling a task with negative delay should throw IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - t.cancel(); - - // Ensure a Timer throws an IllegalArgumentException if period is - // negative - t = new Timer(); - d = new Date(System.currentTimeMillis() + 100); - testTask = new TimerTestTask(); - try { - t.schedule(testTask, d, -100); - fail("Scheduling a task with negative period should throw IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - t.cancel(); - - // Ensure a Timer throws a NullPointerException if the task is null - t = new Timer(); - d = new Date(System.currentTimeMillis() + 100); - try { - t.schedule(null, d, 10); - fail("Scheduling a null task should throw NullPointerException"); - } catch (NullPointerException expected) { - } - t.cancel(); - - // Ensure a Timer throws a NullPointerException if the date is null - t = new Timer(); - testTask = new TimerTestTask(); - try { - t.schedule(testTask, null, 10); - fail("Scheduling a null task should throw NullPointerException"); - } catch (NullPointerException expected) { - } - t.cancel(); - - // Ensure proper sequence of exceptions - t = new Timer(); - d = new Date(-100); - try { - t.schedule(null, d, 10); - fail("Scheduling a null task with negative dates should throw IllegalArgumentException first"); - } catch (IllegalArgumentException expected) { - } - t.cancel(); - - // Ensure a task is run at least twice - t = new Timer(); - d = new Date(System.currentTimeMillis() + 100); - testTask = new TimerTestTask(); - t.schedule(testTask, d, 100); - Thread.sleep(800); - assertTrue("TimerTask.run() method should have been called at least twice (" - + testTask.wasRun() + ")", testTask.wasRun() >= 2); - t.cancel(); - - // Ensure multiple tasks are run - t = new Timer(); - testTask = new TimerTestTask(); - testTask.incrementCount(true); - d = new Date(System.currentTimeMillis() + 100); - t.schedule(testTask, d, 100); // at least 9 times - testTask = new TimerTestTask(); - testTask.incrementCount(true); - d = new Date(System.currentTimeMillis() + 200); - t.schedule(testTask, d, 100); // at least 7 times - testTask = new TimerTestTask(); - testTask.incrementCount(true); - d = new Date(System.currentTimeMillis() + 300); - t.schedule(testTask, d, 200); // at least 4 times - testTask = new TimerTestTask(); - testTask.incrementCount(true); - d = new Date(System.currentTimeMillis() + 100); - t.schedule(testTask, d, 200); // at least 4 times - Thread.sleep(3000); - assertTrue("Multiple tasks should have incremented counter 24 times not " - + timerCounter, timerCounter >= 24); - t.cancel(); - } finally { - if (t != null) - t.cancel(); - } - } - - /** - * java.util.Timer#scheduleAtFixedRate(java.util.TimerTask, long, - * long) - */ - public void test_scheduleAtFixedRateLjava_util_TimerTaskJJ() throws Exception { - Timer t = null; - try { - // Ensure a Timer throws an IllegalStateException after cancelled - t = new Timer(); - TimerTestTask testTask = new TimerTestTask(); - t.cancel(); - try { - t.scheduleAtFixedRate(testTask, 100, 100); - fail("scheduleAtFixedRate after Timer.cancel() should throw exception"); - } catch (IllegalStateException expected) { - } - - // Ensure a Timer throws an IllegalArgumentException if delay is - // negative - t = new Timer(); - testTask = new TimerTestTask(); - try { - t.scheduleAtFixedRate(testTask, -100, 100); - fail("scheduleAtFixedRate with negative delay should throw IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - t.cancel(); - - // Ensure a Timer throws an IllegalArgumentException if period is - // negative - t = new Timer(); - testTask = new TimerTestTask(); - try { - t.scheduleAtFixedRate(testTask, 100, -100); - fail("scheduleAtFixedRate with negative period should throw IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - t.cancel(); - - // Ensure a task is run at least twice - t = new Timer(); - testTask = new TimerTestTask(); - t.scheduleAtFixedRate(testTask, 100, 100); - Thread.sleep(400); - assertTrue("TimerTask.run() method should have been called at least twice (" - + testTask.wasRun() + ")", testTask.wasRun() >= 2); - t.cancel(); - - class SlowThenFastTask extends TimerTask { - int wasRun = 0; - - long startedAt; - - long lastDelta; - - public void run() { - if (wasRun == 0) - startedAt = System.currentTimeMillis(); - lastDelta = System.currentTimeMillis() - - (startedAt + (100 * wasRun)); - wasRun++; - if (wasRun == 2) { - try { - Thread.sleep(200); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } - } - - public long lastDelta() { - return lastDelta; - } - - public int wasRun() { - return wasRun; - } - } - - // Ensure multiple tasks are run - t = new Timer(); - SlowThenFastTask slowThenFastTask = new SlowThenFastTask(); - - // at least 9 times even when asleep - t.scheduleAtFixedRate(slowThenFastTask, 100, 100); - Thread.sleep(1000); - long lastDelta = slowThenFastTask.lastDelta(); - assertTrue("Fixed Rate Schedule should catch up, but is off by " - + lastDelta + " ms", slowThenFastTask.lastDelta < 300); - t.cancel(); - } finally { - if (t != null) - t.cancel(); - } - } - - /** - * java.util.Timer#scheduleAtFixedRate(java.util.TimerTask, - * java.util.Date, long) - */ - public void test_scheduleAtFixedRateLjava_util_TimerTaskLjava_util_DateJ() throws Exception { - Timer t = null; - try { - // Ensure a Timer throws an IllegalStateException after cancelled - t = new Timer(); - TimerTestTask testTask = new TimerTestTask(); - t.cancel(); - Date d = new Date(System.currentTimeMillis() + 100); - try { - t.scheduleAtFixedRate(testTask, d, 100); - fail("scheduleAtFixedRate after Timer.cancel() should throw exception"); - } catch (IllegalStateException expected) { - } - - // Ensure a Timer throws an IllegalArgumentException if delay is - // negative - t = new Timer(); - testTask = new TimerTestTask(); - d = new Date(-100); - try { - t.scheduleAtFixedRate(testTask, d, 100); - fail("scheduleAtFixedRate with negative Date should throw IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - t.cancel(); - - // Ensure a Timer throws an IllegalArgumentException if period is - // negative - t = new Timer(); - testTask = new TimerTestTask(); - try { - t.scheduleAtFixedRate(testTask, d, -100); - fail("scheduleAtFixedRate with negative period should throw IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - t.cancel(); - - // Ensure a Timer throws an NullPointerException if date is Null - t = new Timer(); - testTask = new TimerTestTask(); - try { - t.scheduleAtFixedRate(testTask, null, 100); - fail("scheduleAtFixedRate with null date should throw NullPointerException"); - } catch (NullPointerException expected) { - } - t.cancel(); - - // Ensure proper sequence of exceptions - t = new Timer(); - d = new Date(-100); - try { - t.scheduleAtFixedRate(null, d, 10); - fail("Scheduling a null task with negative date should throw IllegalArgumentException first"); - } catch (IllegalArgumentException expected) { - } - t.cancel(); - - // Ensure proper sequence of exceptions - t = new Timer(); - try { - t.scheduleAtFixedRate(null, null, -10); - fail("Scheduling a null task & null date & negative period should throw IllegalArgumentException first"); - } catch (IllegalArgumentException expected) { - } - t.cancel(); - - // Ensure a task is run at least twice - t = new Timer(); - testTask = new TimerTestTask(); - d = new Date(System.currentTimeMillis() + 100); - t.scheduleAtFixedRate(testTask, d, 100); - Thread.sleep(400); - assertTrue("TimerTask.run() method should have been called at least twice (" - + testTask.wasRun() + ")", testTask.wasRun() >= 2); - t.cancel(); - - class SlowThenFastTask extends TimerTask { - int wasRun = 0; - - long startedAt; - - long lastDelta; - - public void run() { - if (wasRun == 0) - startedAt = System.currentTimeMillis(); - lastDelta = System.currentTimeMillis() - - (startedAt + (100 * wasRun)); - wasRun++; - if (wasRun == 2) { - try { - Thread.sleep(200); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } - } - - public long lastDelta() { - return lastDelta; - } - - public int wasRun() { - return wasRun; - } - } - - // Ensure multiple tasks are run - t = new Timer(); - SlowThenFastTask slowThenFastTask = new SlowThenFastTask(); - d = new Date(System.currentTimeMillis() + 100); - - // at least 9 times even when asleep - t.scheduleAtFixedRate(slowThenFastTask, d, 100); - Thread.sleep(1000); - long lastDelta = slowThenFastTask.lastDelta(); - assertTrue("Fixed Rate Schedule should catch up, but is off by " - + lastDelta + " ms", lastDelta < 300); - t.cancel(); - } finally { - if (t != null) - t.cancel(); - } - } - - /** - * We used to swallow RuntimeExceptions thrown by tasks. Instead, we need to - * let those exceptions bubble up, where they will both notify the thread's - * uncaught exception handler and terminate the timer's thread. - */ - public void testThrowingTaskKillsTimerThread() throws Exception { - final AtomicReference<Thread> threadRef = new AtomicReference<Thread>(); - new Timer().schedule(new TimerTask() { - @Override public void run() { - Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() { - public void uncaughtException(Thread thread, Throwable ex) {} - }); - threadRef.set(Thread.currentThread()); - throw new RuntimeException("task failure!"); - } - }, 1); - - Thread.sleep(400); - Thread timerThread = threadRef.get(); - assertFalse(timerThread.isAlive()); - } - - protected void setUp() { - timerCounter = 0; - } - - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/util/TooManyListenersExceptionTest.java b/luni/src/test/java/tests/api/java/util/TooManyListenersExceptionTest.java deleted file mode 100644 index 48df5fd..0000000 --- a/luni/src/test/java/tests/api/java/util/TooManyListenersExceptionTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.TooManyListenersException; - -public class TooManyListenersExceptionTest extends junit.framework.TestCase { - - /** - * java.util.TooManyListenersException#TooManyListenersException() - */ - public void test_Constructor() { - // Test for method java.util.TooManyListenersException() - try { - throw new TooManyListenersException(); - } catch (TooManyListenersException e) { - assertNull( - "Message thrown with exception constructed with no message", - e.getMessage()); - } - } - - /** - * java.util.TooManyListenersException#TooManyListenersException(java.lang.String) - */ - public void test_ConstructorLjava_lang_String() { - // Test for method java.util.TooManyListenersException(java.lang.String) - try { - throw new TooManyListenersException("Gah"); - } catch (TooManyListenersException e) { - assertEquals("Incorrect message thrown with exception", "Gah", e - .getMessage()); - } - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/util/VectorTest.java b/luni/src/test/java/tests/api/java/util/VectorTest.java deleted file mode 100644 index 6228cb3..0000000 --- a/luni/src/test/java/tests/api/java/util/VectorTest.java +++ /dev/null @@ -1,1198 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Vector; - -import tests.support.Support_ListTest; - -public class VectorTest extends junit.framework.TestCase { - - private Vector tVector = new Vector(); - - Object[] objArray; - - private String vString = "[Test 0, Test 1, Test 2, Test 3, Test 4, Test 5, Test 6, Test 7, Test 8, Test 9, Test 10, Test 11, Test 12, Test 13, Test 14, Test 15, Test 16, Test 17, Test 18, Test 19, Test 20, Test 21, Test 22, Test 23, Test 24, Test 25, Test 26, Test 27, Test 28, Test 29, Test 30, Test 31, Test 32, Test 33, Test 34, Test 35, Test 36, Test 37, Test 38, Test 39, Test 40, Test 41, Test 42, Test 43, Test 44, Test 45, Test 46, Test 47, Test 48, Test 49, Test 50, Test 51, Test 52, Test 53, Test 54, Test 55, Test 56, Test 57, Test 58, Test 59, Test 60, Test 61, Test 62, Test 63, Test 64, Test 65, Test 66, Test 67, Test 68, Test 69, Test 70, Test 71, Test 72, Test 73, Test 74, Test 75, Test 76, Test 77, Test 78, Test 79, Test 80, Test 81, Test 82, Test 83, Test 84, Test 85, Test 86, Test 87, Test 88, Test 89, Test 90, Test 91, Test 92, Test 93, Test 94, Test 95, Test 96, Test 97, Test 98, Test 99]"; - - /** - * java.util.Vector#Vector() - */ - public void test_Constructor() { - // Test for method java.util.Vector() - - Vector tv = new Vector(100); - for (int i = 0; i < 100; i++) - tv.addElement(new Integer(i)); - new Support_ListTest("", tv).runTest(); - - tv = new Vector(200); - for (int i = -50; i < 150; i++) - tv.addElement(new Integer(i)); - new Support_ListTest("", tv.subList(50, 150)).runTest(); - - Vector v = new Vector(); - assertEquals("Vector creation failed", 0, v.size()); - assertEquals("Wrong capacity", 10, v.capacity()); - } - - /** - * java.util.Vector#Vector(int) - */ - public void test_ConstructorI() { - // Test for method java.util.Vector(int) - - Vector v = new Vector(100); - assertEquals("Vector creation failed", 0, v.size()); - assertEquals("Wrong capacity", 100, v.capacity()); - - try { - new Vector(-1); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - } - - /** - * java.util.Vector#Vector(int, int) - */ - public void test_ConstructorII() { - // Test for method java.util.Vector(int, int) - - Vector v = new Vector(2, 10); - v.addElement(new Object()); - v.addElement(new Object()); - v.addElement(new Object()); - - assertEquals("Failed to inc capacity by proper amount", - 12, v.capacity()); - - Vector grow = new Vector(3, -1); - grow.addElement("one"); - grow.addElement("two"); - grow.addElement("three"); - grow.addElement("four"); - assertEquals("Wrong size", 4, grow.size()); - assertEquals("Wrong capacity", 6, grow.capacity()); - - try { - new Vector(-1, 1); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - } - - /** - * java.util.Vector#Vector(java.util.Collection) - */ - public void test_ConstructorLjava_util_Collection() { - // Test for method java.util.Vector(java.util.Collection) - Collection l = new LinkedList(); - for (int i = 0; i < 100; i++) - l.add("Test " + i); - Vector myVector = new Vector(l); - assertTrue("Vector is not correct size", - myVector.size() == objArray.length); - for (int counter = 0; counter < objArray.length; counter++) - assertTrue("Vector does not contain correct elements", myVector - .contains(((List) l).get(counter))); - - try { - new Vector(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.Vector#add(int, java.lang.Object) - */ - public void test_addILjava_lang_Object() { - // Test for method void java.util.Vector.add(int, java.lang.Object) - Object o = new Object(); - Object prev = tVector.get(45); - tVector.add(45, o); - assertTrue("Failed to add Object", tVector.get(45) == o); - assertTrue("Failed to fix-up existing indices", tVector.get(46) == prev); - assertEquals("Wrong size after add", 101, tVector.size()); - - prev = tVector.get(50); - tVector.add(50, null); - assertNull("Failed to add null", tVector.get(50)); - assertTrue("Failed to fix-up existing indices after adding null", - tVector.get(51) == prev); - assertEquals("Wrong size after add", 102, tVector.size()); - - try { - tVector.add(-5, null); - fail("ArrayIndexOutOfBoundsException expected"); - } catch(ArrayIndexOutOfBoundsException e) { - //expected - } - - try { - tVector.add(tVector.size() + 1, null); - fail("ArrayIndexOutOfBoundsException expected"); - } catch(ArrayIndexOutOfBoundsException e) { - //expected - } - } - - /** - * java.util.Vector#add(java.lang.Object) - */ - public void test_addLjava_lang_Object() { - // Test for method boolean java.util.Vector.add(java.lang.Object) - Object o = new Object(); - tVector.add(o); - assertTrue("Failed to add Object", tVector.lastElement() == o); - assertEquals("Wrong size after add", 101, tVector.size()); - - tVector.add(null); - assertNull("Failed to add null", tVector.lastElement()); - assertEquals("Wrong size after add", 102, tVector.size()); - } - - /** - * java.util.Vector#addAll(int, java.util.Collection) - */ - public void test_addAllILjava_util_Collection() { - // Test for method boolean java.util.Vector.addAll(int, - // java.util.Collection) - Collection l = new LinkedList(); - for (int i = 0; i < 100; i++) - l.add("Test " + i); - Vector v = new Vector(); - tVector.addAll(50, l); - for (int i = 50; i < 100; i++) - assertTrue("Failed to add all elements", - tVector.get(i) == ((List) l).get(i - 50)); - v = new Vector(); - v.add("one"); - int r = 0; - try { - v.addAll(3, Arrays.asList(new String[] { "two", "three" })); - } catch (ArrayIndexOutOfBoundsException e) { - r = 1; - } catch (IndexOutOfBoundsException e) { - r = 2; - } - assertTrue("Invalid add: " + r, r == 1); - l = new LinkedList(); - l.add(null); - l.add("gah"); - l.add(null); - tVector.addAll(50, l); - assertNull("Wrong element at position 50--wanted null", - tVector.get(50)); - assertEquals("Wrong element at position 51--wanted 'gah'", "gah", tVector - .get(51)); - assertNull("Wrong element at position 52--wanted null", - tVector.get(52)); - - try { - tVector.addAll(-5, Arrays.asList(new String[] { "two", "three" })); - fail("ArrayIndexOutOfBoundsException expected"); - } catch(ArrayIndexOutOfBoundsException e) { - //expected - } - - try { - tVector.addAll(tVector.size() + 1, Arrays.asList(new String[] { "two", "three" })); - fail("ArrayIndexOutOfBoundsException expected"); - } catch(ArrayIndexOutOfBoundsException e) { - //expected - } - - try { - tVector.addAll(tVector.size() / 2, null); - fail("NullPointerException expected"); - } catch(NullPointerException e) { - //expected - } - } - - /** - * java.util.Vector#addAll(java.util.Collection) - */ - public void test_addAllLjava_util_Collection() { - // Test for method boolean java.util.Vector.addAll(java.util.Collection) - Vector v = new Vector(); - Collection l = new LinkedList(); - for (int i = 0; i < 100; i++) - l.add("Test " + i); - v.addAll(l); - assertTrue("Failed to add all elements", tVector.equals(v)); - - v.addAll(l); - int vSize = tVector.size(); - for (int counter = vSize - 1; counter >= 0; counter--) - assertTrue("Failed to add elements correctly", v.get(counter) == v - .get(counter + vSize)); - - l = new LinkedList(); - l.add(null); - l.add("gah"); - l.add(null); - tVector.addAll(l); - assertNull("Wrong element at 3rd last position--wanted null", tVector - .get(vSize)); - assertEquals("Wrong element at 2nd last position--wanted 'gah'", "gah", tVector - .get(vSize + 1)); - assertNull("Wrong element at last position--wanted null", tVector - .get(vSize + 2)); - - try { - tVector.addAll(tVector.size() / 2, null); - fail("NullPointerException expected"); - } catch(NullPointerException e) { - //expected - } - } - - /** - * java.util.Vector#addElement(java.lang.Object) - */ - public void test_addElementLjava_lang_Object() { - // Test for method void java.util.Vector.addElement(java.lang.Object) - Vector v = vectorClone(tVector); - v.addElement("Added Element"); - assertTrue("Failed to add element", v.contains("Added Element")); - assertEquals("Added Element to wrong slot", "Added Element", ((String) v.elementAt(100)) - ); - v.addElement(null); - assertTrue("Failed to add null", v.contains(null)); - assertNull("Added null to wrong slot", v.elementAt(101)); - } - - /** - * java.util.Vector#addElement(java.lang.Object) - */ - public void test_addElementLjava_lang_Object_subtest0() { - // Test for method void java.util.Vector.addElement(java.lang.Object) - Vector v = vectorClone(tVector); - v.addElement("Added Element"); - assertTrue("Failed to add element", v.contains("Added Element")); - assertEquals("Added Element to wrong slot", "Added Element", ((String) v.elementAt(100)) - ); - v.addElement(null); - assertTrue("Failed to add null", v.contains(null)); - assertNull("Added null to wrong slot", v.elementAt(101)); - } - - /** - * java.util.Vector#capacity() - */ - public void test_capacity() { - // Test for method int java.util.Vector.capacity() - - Vector v = new Vector(9); - assertEquals("Incorrect capacity returned", 9, v.capacity()); - } - - /** - * java.util.Vector#clear() - */ - public void test_clear() { - // Test for method void java.util.Vector.clear() - Vector orgVector = vectorClone(tVector); - tVector.clear(); - assertEquals("a) Cleared Vector has non-zero size", 0, tVector.size()); - Enumeration e = orgVector.elements(); - while (e.hasMoreElements()) - assertTrue("a) Cleared vector contained elements", !tVector - .contains(e.nextElement())); - - tVector.add(null); - tVector.clear(); - assertEquals("b) Cleared Vector has non-zero size", 0, tVector.size()); - e = orgVector.elements(); - while (e.hasMoreElements()) - assertTrue("b) Cleared vector contained elements", !tVector - .contains(e.nextElement())); - } - - /** - * java.util.Vector#clone() - */ - public void test_clone() { - // Test for method java.lang.Object java.util.Vector.clone() - tVector.add(25, null); - tVector.add(75, null); - Vector v = (Vector) tVector.clone(); - Enumeration orgNum = tVector.elements(); - Enumeration cnum = v.elements(); - - while (orgNum.hasMoreElements()) { - assertTrue("Not enough elements copied", cnum.hasMoreElements()); - assertTrue("Vector cloned improperly, elements do not match", - orgNum.nextElement() == cnum.nextElement()); - } - assertTrue("Not enough elements copied", !cnum.hasMoreElements()); - - } - - /** - * java.util.Vector#contains(java.lang.Object) - */ - public void test_containsLjava_lang_Object() { - // Test for method boolean java.util.Vector.contains(java.lang.Object) - assertTrue("Did not find element", tVector.contains("Test 42")); - assertTrue("Found bogus element", !tVector.contains("Hello")); - assertTrue( - "Returned true looking for null in vector without null element", - !tVector.contains(null)); - tVector.insertElementAt(null, 20); - assertTrue( - "Returned false looking for null in vector with null element", - tVector.contains(null)); - } - - /** - * java.util.Vector#containsAll(java.util.Collection) - */ - public void test_containsAllLjava_util_Collection() { - // Test for method boolean - // java.util.Vector.containsAll(java.util.Collection) - Collection s = new HashSet(); - for (int i = 0; i < 100; i++) - s.add("Test " + i); - - assertTrue("Returned false for valid collection", tVector - .containsAll(s)); - s.add(null); - assertTrue("Returned true for invlaid collection containing null", - !tVector.containsAll(s)); - tVector.add(25, null); - assertTrue("Returned false for valid collection containing null", - tVector.containsAll(s)); - s = new HashSet(); - s.add(new Object()); - assertTrue("Returned true for invalid collection", !tVector - .containsAll(s)); - - try { - tVector.containsAll(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.Vector#copyInto(java.lang.Object[]) - */ - public void test_copyInto$Ljava_lang_Object() { - // Test for method void java.util.Vector.copyInto(java.lang.Object []) - - Object[] a = new Object[100]; - tVector.setElementAt(null, 20); - tVector.copyInto(a); - - for (int i = 0; i < 100; i++) - assertTrue("copyInto failed", a[i] == tVector.elementAt(i)); - - try { - tVector.copyInto(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.Vector#elementAt(int) - */ - public void test_elementAtI() { - // Test for method java.lang.Object java.util.Vector.elementAt(int) - assertEquals("Incorrect element returned", "Test 18", ((String) tVector - .elementAt(18))); - tVector.setElementAt(null, 20); - assertNull("Incorrect element returned--wanted null", tVector - .elementAt(20)); - - try { - tVector.elementAt(-5); - fail("ArrayIndexOutOfBoundsException expected"); - } catch(ArrayIndexOutOfBoundsException e) { - //expected - } - - try { - tVector.elementAt(tVector.size() + 1); - fail("ArrayIndexOutOfBoundsException expected"); - } catch(ArrayIndexOutOfBoundsException e) { - //expected - } - } - - /** - * java.util.Vector#elements() - */ - public void test_elements() { - // Test for method java.util.Enumeration java.util.Vector.elements() - tVector.insertElementAt(null, 20); - Enumeration e = tVector.elements(); - int i = 0; - while (e.hasMoreElements()) { - assertTrue("Enumeration returned incorrect element at pos: " + i, e - .nextElement() == tVector.elementAt(i)); - i++; - } - assertTrue("Invalid enumeration", i == tVector.size()); - } - - /** - * java.util.Vector#elements() - */ - public void test_elements_subtest0() { - final int iterations = 10000; - final Vector v = new Vector(); - Thread t1 = new Thread() { - public void run() { - for (int i = 0; i < iterations; i++) { - synchronized (v) { - v.addElement(String.valueOf(i)); - v.removeElementAt(0); - } - } - } - }; - t1.start(); - for (int i = 0; i < iterations; i++) { - Enumeration en = v.elements(); - try { - while (true) { - Object result = en.nextElement(); - if (result == null) { - fail("Null result: " + i); - } - } - } catch (NoSuchElementException e) { - } - } - } - - /** - * java.util.Vector#ensureCapacity(int) - */ - public void test_ensureCapacityI() { - // Test for method void java.util.Vector.ensureCapacity(int) - - Vector v = new Vector(9); - v.ensureCapacity(20); - assertEquals("ensureCapacity failed to set correct capacity", 20, v - .capacity()); - v = new Vector(100); - assertEquals("ensureCapacity reduced capacity", 100, v.capacity()); - } - - /** - * java.util.Vector#equals(java.lang.Object) - */ - public void test_equalsLjava_lang_Object() { - // Test for method boolean java.util.Vector.equals(java.lang.Object) - Vector v = new Vector(); - for (int i = 0; i < 100; i++) - v.addElement("Test " + i); - assertTrue("a) Equal vectors returned false", tVector.equals(v)); - v.addElement(null); - assertTrue("b) UnEqual vectors returned true", !tVector.equals(v)); - tVector.addElement(null); - assertTrue("c) Equal vectors returned false", tVector.equals(v)); - tVector.removeElementAt(22); - assertTrue("d) UnEqual vectors returned true", !tVector.equals(v)); - } - - /** - * java.util.Vector#firstElement() - */ - public void test_firstElement() { - // Test for method java.lang.Object java.util.Vector.firstElement() - assertEquals("Returned incorrect firstElement", "Test 0", tVector.firstElement() - ); - tVector.insertElementAt(null, 0); - assertNull("Returned incorrect firstElement--wanted null", tVector - .firstElement()); - - tVector = new Vector(10); - - try { - tVector.firstElement(); - fail("NoSuchElementException expected"); - } catch (NoSuchElementException e) { - //expected - } - } - - /** - * java.util.Vector#get(int) - */ - public void test_getI() { - // Test for method java.lang.Object java.util.Vector.get(int) - assertEquals("Get returned incorrect object", - "Test 80", tVector.get(80)); - tVector.add(25, null); - assertNull("Returned incorrect element--wanted null", - tVector.get(25)); - - try { - tVector.get(-5); - fail("ArrayIndexOutOfBoundsException expected"); - } catch(ArrayIndexOutOfBoundsException e) { - //expected - } - - try { - tVector.get(tVector.size() + 1); - fail("ArrayIndexOutOfBoundsException expected"); - } catch(ArrayIndexOutOfBoundsException e) { - //expected - } - } - - /** - * java.util.Vector#hashCode() - */ - public void test_hashCode() { - // Test for method int java.util.Vector.hashCode() - int hashCode = 1; // one - tVector.insertElementAt(null, 20); - for (int i = 0; i < tVector.size(); i++) { - Object obj = tVector.elementAt(i); - hashCode = 31 * hashCode + (obj == null ? 0 : obj.hashCode()); - } - assertTrue("Incorrect hashCode returned. Wanted: " + hashCode - + " got: " + tVector.hashCode(), tVector.hashCode() == hashCode); - } - - /** - * java.util.Vector#indexOf(java.lang.Object) - */ - public void test_indexOfLjava_lang_Object() { - // Test for method int java.util.Vector.indexOf(java.lang.Object) - assertEquals("Incorrect index returned", 10, tVector.indexOf("Test 10")); - assertEquals("Index returned for invalid Object", -1, tVector - .indexOf("XXXXXXXXXXX")); - tVector.setElementAt(null, 20); - tVector.setElementAt(null, 40); - assertTrue("Incorrect indexOf returned for null: " - + tVector.indexOf(null), tVector.indexOf(null) == 20); - } - - /** - * java.util.Vector#indexOf(java.lang.Object, int) - */ - public void test_indexOfLjava_lang_ObjectI() { - // Test for method int java.util.Vector.indexOf(java.lang.Object, int) - assertTrue("Failed to find correct index", (tVector.indexOf("Test 98", - 50) == 98)); - assertTrue("Found index of bogus element", (tVector.indexOf( - "Test 1001", 50) == -1)); - tVector.setElementAt(null, 20); - tVector.setElementAt(null, 40); - tVector.setElementAt(null, 60); - assertTrue("a) Incorrect indexOf returned for null: " - + tVector.indexOf(null, 25), tVector.indexOf(null, 25) == 40); - assertTrue("b) Incorrect indexOf returned for null: " - + tVector.indexOf(null, 20), tVector.indexOf(null, 20) == 20); - - try { - tVector.indexOf(null, -1); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - //expected - } - } - - /** - * java.util.Vector#insertElementAt(java.lang.Object, int) - */ - public void test_insertElementAtLjava_lang_ObjectI() { - // Test for method void - // java.util.Vector.insertElementAt(java.lang.Object, int) - Vector v = vectorClone(tVector); - String prevElement = (String) v.elementAt(99); - v.insertElementAt("Inserted Element", 99); - assertEquals("Element not inserted", "Inserted Element", ((String) v.elementAt(99)) - ); - assertTrue("Elements shifted incorrectly", ((String) v.elementAt(100)) - .equals(prevElement)); - v.insertElementAt(null, 20); - assertNull("null not inserted", v.elementAt(20)); - - try { - tVector.insertElementAt(null, -5); - fail("ArrayIndexOutOfBoundsException expected"); - } catch(ArrayIndexOutOfBoundsException e) { - //expected - } - - try { - tVector.insertElementAt(null, tVector.size() + 1); - fail("ArrayIndexOutOfBoundsException expected"); - } catch(ArrayIndexOutOfBoundsException e) { - //expected - } - } - - /** - * java.util.Vector#isEmpty() - */ - public void test_isEmpty() { - // Test for method boolean java.util.Vector.isEmpty()Vector - Vector v = new java.util.Vector(); - assertTrue("Empty vector returned false", v.isEmpty()); - v.addElement(new Object()); - assertTrue("non-Empty vector returned true", !v.isEmpty()); - } - - /** - * java.util.Vector#isEmpty() - */ - public void test_isEmpty_subtest0() { - final Vector v = new Vector(); - v.addElement("initial"); - Thread t1 = new Thread() { - public void run() { - while (!v.isEmpty()) - ; - v.addElement("final"); - } - }; - t1.start(); - for (int i = 0; i < 10000; i++) { - synchronized (v) { - v.removeElementAt(0); - v.addElement(String.valueOf(i)); - } - int size; - if ((size = v.size()) != 1) { - String result = "Size is not 1: " + size + " " + v; - // terminate the thread - v.removeAllElements(); - fail(result); - } - } - // terminate the thread - v.removeElementAt(0); - } - - /** - * java.util.Vector#lastElement() - */ - public void test_lastElement() { - // Test for method java.lang.Object java.util.Vector.lastElement() - assertEquals("Incorrect last element returned", "Test 99", tVector.lastElement() - ); - tVector.addElement(null); - assertNull("Incorrect last element returned--wanted null", tVector - .lastElement()); - - tVector = new Vector(10); - - try { - tVector.lastElement(); - fail("NoSuchElementException expected"); - } catch (NoSuchElementException e) { - //expected - } - } - - /** - * java.util.Vector#lastIndexOf(java.lang.Object) - */ - public void test_lastIndexOfLjava_lang_Object() { - // Test for method int java.util.Vector.lastIndexOf(java.lang.Object) - Vector v = new Vector(9); - for (int i = 0; i < 9; i++) - v.addElement("Test"); - v.addElement("z"); - assertEquals("Failed to return correct index", 8, v.lastIndexOf("Test")); - tVector.setElementAt(null, 20); - tVector.setElementAt(null, 40); - assertTrue("Incorrect lastIndexOf returned for null: " - + tVector.lastIndexOf(null), tVector.lastIndexOf(null) == 40); - } - - /** - * java.util.Vector#lastIndexOf(java.lang.Object, int) - */ - public void test_lastIndexOfLjava_lang_ObjectI() { - // Test for method int java.util.Vector.lastIndexOf(java.lang.Object, - // int) - assertEquals("Failed to find object", - 0, tVector.lastIndexOf("Test 0", 0)); - assertTrue("Found Object outside of index", (tVector.lastIndexOf( - "Test 0", 10) > -1)); - tVector.setElementAt(null, 20); - tVector.setElementAt(null, 40); - tVector.setElementAt(null, 60); - assertTrue("Incorrect lastIndexOf returned for null: " - + tVector.lastIndexOf(null, 15), - tVector.lastIndexOf(null, 15) == -1); - assertTrue("Incorrect lastIndexOf returned for null: " - + tVector.lastIndexOf(null, 45), - tVector.lastIndexOf(null, 45) == 40); - - try { - tVector.lastIndexOf(null, tVector.size()); - fail("IndexOutOfBoundsException expected"); - } catch (IndexOutOfBoundsException e) { - //expected - } - } - - /** - * java.util.Vector#remove(int) - */ - public void test_removeI() { - // Test for method java.lang.Object java.util.Vector.remove(int) - tVector.remove(36); - assertTrue("Contained element after remove", !tVector - .contains("Test 36")); - assertEquals("Failed to decrement size after remove", - 99, tVector.size()); - tVector.add(20, null); - tVector.remove(19); - assertNull("Didn't move null element over", tVector.get(19)); - tVector.remove(19); - assertNotNull("Didn't remove null element", tVector.get(19)); - assertEquals("Failed to decrement size after removing null", 98, tVector - .size()); - - try { - tVector.remove(-5); - fail("ArrayIndexOutOfBoundsException expected"); - } catch(ArrayIndexOutOfBoundsException e) { - //expected - } - - try { - tVector.remove(tVector.size() + 1); - fail("ArrayIndexOutOfBoundsException expected"); - } catch(ArrayIndexOutOfBoundsException e) { - //expected - } - } - - /** - * java.util.Vector#remove(java.lang.Object) - */ - public void test_removeLjava_lang_Object() { - // Test for method boolean java.util.Vector.remove(java.lang.Object) - tVector.remove("Test 0"); - assertTrue("Contained element after remove", !tVector - .contains("Test 0")); - assertEquals("Failed to decrement size after remove", - 99, tVector.size()); - tVector.add(null); - tVector.remove(null); - assertTrue("Contained null after remove", !tVector.contains(null)); - assertEquals("Failed to decrement size after removing null", 99, tVector - .size()); - } - - /** - * java.util.Vector#removeAll(java.util.Collection) - */ - public void test_removeAllLjava_util_Collection() { - // Test for method boolean - // java.util.Vector.removeAll(java.util.Collection) - Vector v = new Vector(); - Collection l = new LinkedList(); - for (int i = 0; i < 5; i++) - l.add("Test " + i); - v.addElement(l); - - Collection s = new HashSet(); - Object o; - s.add(o = v.firstElement()); - v.removeAll(s); - assertTrue("Failed to remove items in collection", !v.contains(o)); - v.removeAll(l); - assertTrue("Failed to remove all elements", v.isEmpty()); - - v.add(null); - v.add(null); - v.add("Boom"); - v.removeAll(s); - assertEquals("Should not have removed any elements", 3, v.size()); - l = new LinkedList(); - l.add(null); - v.removeAll(l); - assertEquals("Should only have one element", 1, v.size()); - assertEquals("Element should be 'Boom'", "Boom", v.firstElement()); - - try { - v.removeAll(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.Vector#removeAllElements() - */ - public void test_removeAllElements() { - // Test for method void java.util.Vector.removeAllElements() - Vector v = vectorClone(tVector); - v.removeAllElements(); - assertEquals("Failed to remove all elements", 0, v.size()); - } - - /** - * java.util.Vector#removeElement(java.lang.Object) - */ - public void test_removeElementLjava_lang_Object() { - // Test for method boolean - // java.util.Vector.removeElement(java.lang.Object) - Vector v = vectorClone(tVector); - v.removeElement("Test 98"); - assertEquals("Element not removed", "Test 99", ((String) v.elementAt(98)) - ); - assertTrue("Vector is wrong size after removal: " + v.size(), - v.size() == 99); - tVector.addElement(null); - v.removeElement(null); - assertTrue("Vector is wrong size after removing null: " + v.size(), v - .size() == 99); - } - - /** - * java.util.Vector#removeElementAt(int) - */ - public void test_removeElementAtI() { - // Test for method void java.util.Vector.removeElementAt(int) - Vector v = vectorClone(tVector); - v.removeElementAt(50); - assertEquals("Failed to remove element", -1, v.indexOf("Test 50", 0)); - tVector.insertElementAt(null, 60); - tVector.removeElementAt(60); - assertNotNull("Element at 60 should not be null after removal", tVector - .elementAt(60)); - - try { - tVector.elementAt(-5); - fail("ArrayIndexOutOfBoundsException expected"); - } catch(ArrayIndexOutOfBoundsException e) { - //expected - } - - try { - tVector.elementAt(tVector.size() + 1); - fail("ArrayIndexOutOfBoundsException expected"); - } catch(ArrayIndexOutOfBoundsException e) { - //expected - } - } - - /** - * java.util.Vector#retainAll(java.util.Collection) - */ - public void test_retainAllLjava_util_Collection() { - // Test for method boolean - // java.util.Vector.retainAll(java.util.Collection) - Object o = tVector.firstElement(); - tVector.add(null); - Collection s = new HashSet(); - s.add(o); - s.add(null); - tVector.retainAll(s); - assertTrue("Retained items other than specified", tVector.size() == 2 - && tVector.contains(o) && tVector.contains(null)); - - Iterator i = s.iterator(); - - while (i.hasNext()) { - assertTrue(tVector.contains(i.next())); - } - - try { - tVector.retainAll(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.Vector#set(int, java.lang.Object) - */ - public void test_setILjava_lang_Object() { - // Test for method java.lang.Object java.util.Vector.set(int, - // java.lang.Object) - Object o = new Object(); - tVector.set(23, o); - assertTrue("Failed to set Object", tVector.get(23) == o); - - try { - tVector.set(-5, "Wrong position"); - fail("ArrayIndexOutOfBoundsException expected"); - } catch(ArrayIndexOutOfBoundsException e) { - //expected - } - - try { - tVector.set(tVector.size() + 1, "Wrong position"); - fail("ArrayIndexOutOfBoundsException expected"); - } catch(ArrayIndexOutOfBoundsException e) { - //expected - } - } - - /** - * java.util.Vector#setElementAt(java.lang.Object, int) - */ - public void test_setElementAtLjava_lang_ObjectI() { - // Test for method void java.util.Vector.setElementAt(java.lang.Object, - // int) - Vector v = vectorClone(tVector); - v.setElementAt("Inserted Element", 99); - assertEquals("Element not set", "Inserted Element", ((String) v.elementAt(99)) - ); - - try { - tVector.setElementAt("Wrong position", -5); - fail("ArrayIndexOutOfBoundsException expected"); - } catch(ArrayIndexOutOfBoundsException e) { - //expected - } - - try { - tVector.setElementAt("Wrong position", tVector.size() + 1); - fail("ArrayIndexOutOfBoundsException expected"); - } catch(ArrayIndexOutOfBoundsException e) { - //expected - } - } - - /** - * java.util.Vector#setSize(int) - */ - public void test_setSizeI() { - // Test for method void java.util.Vector.setSize(int) - Vector v = vectorClone(tVector); - v.setSize(10); - assertEquals("Failed to set size", 10, v.size()); - - try { - tVector.setSize(-5); - fail("ArrayIndexOutOfBoundsException expected"); - } catch(ArrayIndexOutOfBoundsException e) { - //expected - } - } - - /** - * java.util.Vector#size() - */ - public void test_size() { - // Test for method int java.util.Vector.size() - assertEquals("Returned incorrect size", 100, tVector.size()); - - final Vector v = new Vector(); - v.addElement("initial"); - Thread t1 = new Thread() { - public void run() { - while (v.size() > 0) - ; - v.addElement("final"); - } - }; - t1.start(); - for (int i = 0; i < 10000; i++) { - synchronized (v) { - v.removeElementAt(0); - v.addElement(String.valueOf(i)); - } - int size; - if ((size = v.size()) != 1) { - String result = "Size is not 1: " + size + " " + v; - // terminate the thread - v.removeAllElements(); - fail(result); - } - } - // terminate the thread - v.removeElementAt(0); - } - - /** - * java.util.Vector#subList(int, int) - */ - public void test_subListII() { - // Test for method java.util.List java.util.Vector.subList(int, int) - List sl = tVector.subList(10, 25); - assertEquals("Returned sublist of incorrect size", 15, sl.size()); - for (int i = 10; i < 25; i++) - assertTrue("Returned incorrect sublist", sl - .contains(tVector.get(i))); - - assertEquals("Not synchronized random access", "java.util.Collections$SynchronizedRandomAccessList", sl.getClass().getName() - ); - - try { - tVector.subList(-10, 25); - fail("IndexOutOfBoundsException expected"); - } catch(IndexOutOfBoundsException e) { - //expected - } - - try { - tVector.subList(10, tVector.size() + 1); - fail("IndexOutOfBoundsException expected"); - } catch(IndexOutOfBoundsException e) { - //expected - } - - try { - tVector.subList(25, 10); - fail("IllegalArgumentException expected"); - } catch(IllegalArgumentException e) { - //expected - } - } - - /** - * java.util.Vector#toArray() - */ - public void test_toArray() { - // Test for method java.lang.Object [] java.util.Vector.toArray() - assertTrue("Returned incorrect array", Arrays.equals(objArray, tVector - .toArray())); - } - - /** - * java.util.Vector#toArray(java.lang.Object[]) - */ - public void test_toArray$Ljava_lang_Object() { - // Test for method java.lang.Object [] - // java.util.Vector.toArray(java.lang.Object []) - Object[] o = new Object[1000]; - Object f = new Object(); - for (int i = 0; i < o.length; i++) - o[i] = f; - tVector.toArray(o); - assertNull("Failed to set slot to null", o[100]); - for (int i = 0; i < tVector.size(); i++) - assertTrue("Returned incorrect array", tVector.elementAt(i) == o[i]); - - try { - tVector.toArray(null); - fail("NullPointerException expected"); - } catch(NullPointerException e) { - //expected - } - tVector = new Vector<Integer>(); - tVector.add(new Integer(1)); - tVector.add(new Integer(2)); - tVector.add(new Integer(3)); - try { - tVector.toArray(new String[tVector.size()]); - fail("ArrayStoreException expected"); - } catch(ArrayStoreException e) { - //expected - } - } - - /** - * java.util.Vector#toString() - */ - public void test_toString() { - // Test for method java.lang.String java.util.Vector.toString() - assertTrue("Incorrect String returned", tVector.toString().equals( - vString)); - - Vector v = new Vector(); - v.addElement("one"); - v.addElement(v); - v.addElement("3"); - // test last element - v.addElement(v); - String result = v.toString(); - assertTrue("should contain self ref", result.indexOf("(this") > -1); - } - - /** - * java.util.Vector#trimToSize() - */ - public void test_trimToSize() { - // Test for method void java.util.Vector.trimToSize() - Vector v = new Vector(10); - v.addElement(new Object()); - v.trimToSize(); - assertEquals("Failed to trim capacity", 1, v.capacity()); - } - - class Mock_Vector extends Vector { - @Override - protected void removeRange(int from, int to) { - super.removeRange(from, to); - } - } - - public void test_removeRangeII() { - Mock_Vector mv = new Mock_Vector(); - mv.add("First"); - mv.add("Second"); - mv.add("One more"); - mv.add("Last"); - mv.removeRange(1, 3); - assertTrue(mv.contains("First")); - assertFalse(mv.contains("Second")); - assertFalse(mv.contains("One more")); - assertTrue(mv.contains("Last")); - } - - protected Vector vectorClone(Vector s) { - return (Vector) s.clone(); - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - for (int i = 0; i < 100; i++) { - tVector.addElement("Test " + i); - } - objArray = new Object[100]; - for (int i = 0; i < 100; i++) { - objArray[i] = "Test " + i; - } - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/util/WeakHashMapTest.java b/luni/src/test/java/tests/api/java/util/WeakHashMapTest.java deleted file mode 100644 index d1a43e5..0000000 --- a/luni/src/test/java/tests/api/java/util/WeakHashMapTest.java +++ /dev/null @@ -1,383 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.java.util; - -import java.util.AbstractMap; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.WeakHashMap; -import libcore.java.lang.ref.FinalizationTester; - -import tests.support.Support_MapTest2; - -public class WeakHashMapTest extends junit.framework.TestCase { - class MockMap extends AbstractMap { - public Set entrySet() { - return null; - } - public int size(){ - return 0; - } - } - - Object[] keyArray = new Object[100]; - - Object[] valueArray = new Object[100]; - - WeakHashMap whm; - - /** - * java.util.WeakHashMap#WeakHashMap() - */ - public void test_Constructor() { - // Test for method java.util.WeakHashMap() - new Support_MapTest2(new WeakHashMap()).runTest(); - - whm = new WeakHashMap(); - for (int i = 0; i < 100; i++) - whm.put(keyArray[i], valueArray[i]); - for (int i = 0; i < 100; i++) - assertTrue("Incorrect value retrieved", - whm.get(keyArray[i]) == valueArray[i]); - - } - - /** - * java.util.WeakHashMap#WeakHashMap(int) - */ - public void test_ConstructorI() { - // Test for method java.util.WeakHashMap(int) - whm = new WeakHashMap(50); - for (int i = 0; i < 100; i++) - whm.put(keyArray[i], valueArray[i]); - for (int i = 0; i < 100; i++) - assertTrue("Incorrect value retrieved", - whm.get(keyArray[i]) == valueArray[i]); - - WeakHashMap empty = new WeakHashMap(0); - assertNull("Empty weakhashmap access", empty.get("nothing")); - empty.put("something", "here"); - assertTrue("cannot get element", empty.get("something") == "here"); - - try { - new WeakHashMap(-50); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - } - - /** - * java.util.WeakHashMap#WeakHashMap(int, float) - */ - public void test_ConstructorIF() { - // Test for method java.util.WeakHashMap(int, float) - whm = new WeakHashMap(50, 0.5f); - for (int i = 0; i < 100; i++) - whm.put(keyArray[i], valueArray[i]); - for (int i = 0; i < 100; i++) - assertTrue("Incorrect value retrieved", - whm.get(keyArray[i]) == valueArray[i]); - - WeakHashMap empty = new WeakHashMap(0, 0.75f); - assertNull("Empty hashtable access", empty.get("nothing")); - empty.put("something", "here"); - assertTrue("cannot get element", empty.get("something") == "here"); - - try { - new WeakHashMap(50, -0.5f); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - - try { - new WeakHashMap(-50, 0.5f); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - //expected - } - } - - /** - * java.util.WeakHashMap#WeakHashMap(java.util.Map) - */ - public void test_ConstructorLjava_util_Map() { - Map mockMap = new MockMap(); - WeakHashMap map = new WeakHashMap(mockMap); - assertEquals("Size should be 0", 0, map.size()); - - try { - new WeakHashMap(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.WeakHashMap#clear() - */ - public void test_clear() { - // Test for method boolean java.util.WeakHashMap.clear() - whm = new WeakHashMap(); - for (int i = 0; i < 100; i++) - whm.put(keyArray[i], valueArray[i]); - whm.clear(); - assertTrue("Cleared map should be empty", whm.isEmpty()); - for (int i = 0; i < 100; i++) - assertNull("Cleared map should only return null", whm - .get(keyArray[i])); - - } - - /** - * java.util.WeakHashMap#containsKey(java.lang.Object) - */ - public void test_containsKeyLjava_lang_Object() { - // Test for method boolean java.util.WeakHashMap.containsKey() - whm = new WeakHashMap(); - for (int i = 0; i < 100; i++) - whm.put(keyArray[i], valueArray[i]); - for (int i = 0; i < 100; i++) - assertTrue("Should contain referenced key", whm - .containsKey(keyArray[i])); - keyArray[25] = null; - keyArray[50] = null; - } - - /** - * java.util.WeakHashMap#containsValue(java.lang.Object) - */ - public void test_containsValueLjava_lang_Object() { - // Test for method boolean java.util.WeakHashMap.containsValue() - whm = new WeakHashMap(); - for (int i = 0; i < 100; i++) - whm.put(keyArray[i], valueArray[i]); - for (int i = 0; i < 100; i++) - assertTrue("Should contain referenced value", whm - .containsValue(valueArray[i])); - keyArray[25] = null; - keyArray[50] = null; - } - - /** - * java.util.WeakHashMap#entrySet() - */ - public void test_entrySet() { - // Test for method java.util.Set java.util.WeakHashMap.entrySet() - whm = new WeakHashMap(); - for (int i = 0; i < 100; i++) - whm.put(keyArray[i], valueArray[i]); - List keys = Arrays.asList(keyArray); - List values = Arrays.asList(valueArray); - Set entrySet = whm.entrySet(); - assertTrue("Incorrect number of entries returned--wanted 100, got: " - + entrySet.size(), entrySet.size() == 100); - Iterator it = entrySet.iterator(); - while (it.hasNext()) { - Map.Entry entry = (Map.Entry) it.next(); - assertTrue("Invalid map entry returned--bad key", keys - .contains(entry.getKey())); - assertTrue("Invalid map entry returned--bad key", values - .contains(entry.getValue())); - } - keys = null; - values = null; - keyArray[50] = null; - - int count = 0; - do { - System.gc(); - System.gc(); - FinalizationTester.induceFinalization(); - count++; - } while (count <= 5 && entrySet.size() == 100); - - assertTrue( - "Incorrect number of entries returned after gc--wanted 99, got: " - + entrySet.size(), entrySet.size() == 99); - } - - /** - * java.util.WeakHashMap#isEmpty() - */ - public void test_isEmpty() { - // Test for method boolean java.util.WeakHashMap.isEmpty() - whm = new WeakHashMap(); - assertTrue("New map should be empty", whm.isEmpty()); - Object myObject = new Object(); - whm.put(myObject, myObject); - assertTrue("Map should not be empty", !whm.isEmpty()); - whm.remove(myObject); - assertTrue("Map with elements removed should be empty", whm.isEmpty()); - } - - /** - * java.util.WeakHashMap#put(java.lang.Object, java.lang.Object) - */ - public void test_putLjava_lang_ObjectLjava_lang_Object() { - // Test for method java.lang.Object - // java.util.WeakHashMap.put(java.lang.Object, java.lang.Object) - WeakHashMap map = new WeakHashMap(); - map.put(null, "value"); // add null key - System.gc(); - System.gc(); - FinalizationTester.induceFinalization(); - map.remove("nothing"); // Cause objects in queue to be removed - assertEquals("null key was removed", 1, map.size()); - } - - /** - * java.util.WeakHashMap#putAll(java.util.Map) - */ - public void test_putAllLjava_util_Map() { - Map mockMap=new MockMap(); - WeakHashMap map = new WeakHashMap(); - map.putAll(mockMap); - assertEquals("Size should be 0", 0, map.size()); - - try { - map.putAll(null); - fail("NullPointerException exected"); - } catch (NullPointerException e) { - //expected - } - } - - /** - * java.util.WeakHashMap#remove(java.lang.Object) - */ - public void test_removeLjava_lang_Object() { - // Test for method java.lang.Object - // java.util.WeakHashMap.remove(java.lang.Object) - whm = new WeakHashMap(); - for (int i = 0; i < 100; i++) - whm.put(keyArray[i], valueArray[i]); - - assertTrue("Remove returned incorrect value", - whm.remove(keyArray[25]) == valueArray[25]); - assertNull("Remove returned incorrect value", - whm.remove(keyArray[25])); - assertEquals("Size should be 99 after remove", 99, whm.size()); - } - - /** - * java.util.WeakHashMap#size() - */ - public void test_size() { - whm = new WeakHashMap(); - assertEquals(0, whm.size()); - } - - /** - * java.util.WeakHashMap#keySet() - */ - public void test_keySet() { - // Test for method java.util.Set java.util.WeakHashMap.keySet() - whm = new WeakHashMap(); - for (int i = 0; i < 100; i++) - whm.put(keyArray[i], valueArray[i]); - - List keys = Arrays.asList(keyArray); - List values = Arrays.asList(valueArray); - - Set keySet = whm.keySet(); - assertEquals("Incorrect number of keys returned,", 100, keySet.size()); - Iterator it = keySet.iterator(); - while (it.hasNext()) { - Object key = it.next(); - assertTrue("Invalid map entry returned--bad key", keys - .contains(key)); - } - keys = null; - values = null; - keyArray[50] = null; - - int count = 0; - do { - System.gc(); - System.gc(); - FinalizationTester.induceFinalization(); - count++; - } while (count <= 5 && keySet.size() == 100); - - assertEquals("Incorrect number of keys returned after gc,", 99, keySet - .size()); - } - - /** - * java.util.WeakHashMap#values() - */ - public void test_values() { - // Test for method java.util.Set java.util.WeakHashMap.values() - whm = new WeakHashMap(); - for (int i = 0; i < 100; i++) - whm.put(keyArray[i], valueArray[i]); - - List keys = Arrays.asList(keyArray); - List values = Arrays.asList(valueArray); - - Collection valuesCollection = whm.values(); - assertEquals("Incorrect number of keys returned,", 100, - valuesCollection.size()); - Iterator it = valuesCollection.iterator(); - while (it.hasNext()) { - Object value = it.next(); - assertTrue("Invalid map entry returned--bad value", values - .contains(value)); - } - keys = null; - values = null; - keyArray[50] = null; - - int count = 0; - do { - System.gc(); - System.gc(); - FinalizationTester.induceFinalization(); - count++; - } while (count <= 5 && valuesCollection.size() == 100); - - assertEquals("Incorrect number of keys returned after gc,", 99, - valuesCollection.size()); - } - - /** - * Sets up the fixture, for example, open a network connection. This method - * is called before a test is executed. - */ - protected void setUp() { - for (int i = 0; i < 100; i++) { - keyArray[i] = new Object(); - valueArray[i] = new Object(); - } - - } - - /** - * Tears down the fixture, for example, close a network connection. This - * method is called after a test is executed. - */ - protected void tearDown() { - } -} diff --git a/luni/src/test/java/tests/api/java/util/support/A.java b/luni/src/test/java/tests/api/java/util/support/A.java deleted file mode 100644 index c2b43b5..0000000 --- a/luni/src/test/java/tests/api/java/util/support/A.java +++ /dev/null @@ -1,13 +0,0 @@ -package tests.api.java.util.support; - -public class A implements I { - private static P pp = new P(); - - public A() { - pp.setClazz(getClass()); - } - - public String find(String key) { - return pp.findProp(key); - } -} diff --git a/luni/src/test/java/tests/api/java/util/support/B.java b/luni/src/test/java/tests/api/java/util/support/B.java deleted file mode 100644 index baafdbe..0000000 --- a/luni/src/test/java/tests/api/java/util/support/B.java +++ /dev/null @@ -1,4 +0,0 @@ -package tests.api.java.util.support; - -public class B extends A { -} diff --git a/luni/src/test/java/tests/api/java/util/support/I.java b/luni/src/test/java/tests/api/java/util/support/I.java deleted file mode 100644 index a1cd73a..0000000 --- a/luni/src/test/java/tests/api/java/util/support/I.java +++ /dev/null @@ -1,5 +0,0 @@ -package tests.api.java.util.support; - -public interface I { - String find(String key); -} diff --git a/luni/src/test/java/tests/api/java/util/support/P.java b/luni/src/test/java/tests/api/java/util/support/P.java deleted file mode 100644 index 6883936..0000000 --- a/luni/src/test/java/tests/api/java/util/support/P.java +++ /dev/null @@ -1,28 +0,0 @@ -package tests.api.java.util.support; - -import java.util.ResourceBundle; - -public class P { - private Class c; - - public void setClazz(Class c) { - this.c = c; - } - - public String findProp(String key) { - return findProp(this.c, key); - } - - private String findProp(Class cls, String key) { - String ret = null; - try { - ResourceBundle b = ResourceBundle.getBundle(cls.getName()); - ret = (String)b.getObject(key); - } catch (Exception e) { - } - if (ret == null && !cls.equals(Object.class) && !cls.isPrimitive()) { - ret = findProp(cls.getSuperclass(), key); - } - return ret; - } -} diff --git a/luni/src/test/java/tests/api/javax/net/ServerSocketFactoryTest.java b/luni/src/test/java/tests/api/javax/net/ServerSocketFactoryTest.java deleted file mode 100644 index 34d7aed..0000000 --- a/luni/src/test/java/tests/api/javax/net/ServerSocketFactoryTest.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -/** -* @author Boris V. Kuznetsov -* @version $Revision$ -*/ - -package tests.api.javax.net; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.ServerSocket; -import java.net.SocketException; -import javax.net.ServerSocketFactory; - -import junit.framework.TestCase; - -public class ServerSocketFactoryTest extends TestCase { - - public void test_Constructor() { - ServerSocketFactory sf = new MyServerSocketFactory(); - } - - public final void test_createServerSocket() throws Exception { - ServerSocketFactory sf = ServerSocketFactory.getDefault(); - ServerSocket ss = sf.createServerSocket(); - assertNotNull(ss); - ss.close(); - } - - public final void test_createServerSocket_I() throws Exception { - ServerSocketFactory sf = ServerSocketFactory.getDefault(); - ServerSocket ss = sf.createServerSocket(0); - assertNotNull(ss); - - try { - sf.createServerSocket(ss.getLocalPort()); - fail("IOException wasn't thrown"); - } catch (IOException expected) { - } - - ss.close(); - - try { - sf.createServerSocket(-1); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException expected) { - } - } - - public final void test_createServerSocket_II() throws Exception { - ServerSocketFactory sf = ServerSocketFactory.getDefault(); - ServerSocket ss = sf.createServerSocket(0, 0); - assertNotNull(ss); - - try { - sf.createServerSocket(ss.getLocalPort(), 0); - fail("IOException wasn't thrown"); - } catch (IOException expected) { - } - - ss.close(); - - try { - sf.createServerSocket(65536, 0); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException expected) { - } - } - - public final void test_createServerSocket_IIInetAddress() throws Exception { - ServerSocketFactory sf = ServerSocketFactory.getDefault(); - - ServerSocket ss = sf.createServerSocket(0, 0, InetAddress.getLocalHost()); - assertNotNull(ss); - - try { - sf.createServerSocket(ss.getLocalPort(), 0, InetAddress.getLocalHost()); - fail("IOException wasn't thrown"); - } catch (IOException expected) { - } - - ss.close(); - - try { - sf.createServerSocket(Integer.MAX_VALUE, 0, InetAddress.getLocalHost()); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException expected) { - } - } -} -class MyServerSocketFactory extends ServerSocketFactory { - - public MyServerSocketFactory() { - super(); - } - - @Override - public ServerSocket createServerSocket(int port) throws IOException { - return null; - } - - @Override - public ServerSocket createServerSocket(int port, int backlog) - throws IOException { - return null; - } - - @Override - public ServerSocket createServerSocket(int port, int backlog, - InetAddress address) throws IOException { - return null; - } -} diff --git a/luni/src/test/java/tests/api/javax/net/SocketFactoryTest.java b/luni/src/test/java/tests/api/javax/net/SocketFactoryTest.java deleted file mode 100644 index e939a9b..0000000 --- a/luni/src/test/java/tests/api/javax/net/SocketFactoryTest.java +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -/** -* @author Boris V. Kuznetsov -* @version $Revision$ -*/ - -package tests.api.javax.net; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.SocketException; -import java.net.UnknownHostException; - -import javax.net.SocketFactory; - -import junit.framework.TestCase; - -public class SocketFactoryTest extends TestCase { - - public void test_Constructor() throws Exception { - new MySocketFactory(); - } - - public final void test_createSocket() throws Exception { - SocketFactory sf = SocketFactory.getDefault(); - - Socket s = sf.createSocket(); - assertNotNull(s); - assertEquals(-1, s.getLocalPort()); - assertEquals(0, s.getPort()); - - MySocketFactory msf = new MySocketFactory(); - try { - msf.createSocket(); - fail("No expected SocketException"); - } catch (SocketException expected) { - } - } - - public final void test_createSocket_StringI() throws Exception { - SocketFactory sf = SocketFactory.getDefault(); - int sport = new ServerSocket(0).getLocalPort(); - int[] invalidPorts = {Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE}; - - Socket s = sf.createSocket(InetAddress.getLocalHost().getHostName(), sport); - assertNotNull(s); - assertTrue("Failed to create socket", s.getPort() == sport); - - try { - sf.createSocket("bla-bla", sport); - fail("UnknownHostException wasn't thrown"); - } catch (UnknownHostException expected) { - } - - for (int i = 0; i < invalidPorts.length; i++) { - try { - sf.createSocket(InetAddress.getLocalHost().getHostName(), invalidPorts[i]); - fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]); - } catch (IllegalArgumentException expected) { - } - } - - try { - sf.createSocket(InetAddress.getLocalHost().getHostName(), s.getLocalPort()); - fail("IOException wasn't thrown"); - } catch (IOException expected) { - } - - SocketFactory f = SocketFactory.getDefault(); - try { - f.createSocket(InetAddress.getLocalHost().getHostName(), 8082); - fail("IOException wasn't thrown ..."); - } catch (IOException expected) { - } - } - - public final void test_createSocket_InetAddressI() throws Exception { - SocketFactory sf = SocketFactory.getDefault(); - int sport = new ServerSocket(0).getLocalPort(); - int[] invalidPorts = {Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE}; - - Socket s = sf.createSocket(InetAddress.getLocalHost(), sport); - assertNotNull(s); - assertTrue("Failed to create socket", s.getPort() == sport); - - for (int i = 0; i < invalidPorts.length; i++) { - try { - sf.createSocket(InetAddress.getLocalHost(), invalidPorts[i]); - fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]); - } catch (IllegalArgumentException expected) { - } - } - - try { - sf.createSocket(InetAddress.getLocalHost(), s.getLocalPort()); - fail("IOException wasn't thrown"); - } catch (IOException expected) { - } - - SocketFactory f = SocketFactory.getDefault(); - try { - f.createSocket(InetAddress.getLocalHost(), 8081); - fail("IOException wasn't thrown ..."); - } catch (IOException expected) { - } - } - - public final void test_createSocket_InetAddressIInetAddressI() throws Exception { - SocketFactory sf = SocketFactory.getDefault(); - int sport = new ServerSocket(0).getLocalPort(); - int[] invalidPorts = {Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE}; - - Socket s = sf.createSocket(InetAddress.getLocalHost(), sport, - InetAddress.getLocalHost(), 0); - assertNotNull(s); - assertTrue("1: Failed to create socket", s.getPort() == sport); - int portNumber = s.getLocalPort(); - - for (int i = 0; i < invalidPorts.length; i++) { - try { - sf.createSocket(InetAddress.getLocalHost(), invalidPorts[i], - InetAddress.getLocalHost(), portNumber); - fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]); - } catch (IllegalArgumentException expected) { - } - - try { - sf.createSocket(InetAddress.getLocalHost(), sport, - InetAddress.getLocalHost(), invalidPorts[i]); - fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]); - } catch (IllegalArgumentException expected) { - } - } - - try { - sf.createSocket(InetAddress.getLocalHost(), sport, - InetAddress.getLocalHost(), portNumber); - fail("IOException wasn't thrown"); - } catch (IOException expected) { - } - - SocketFactory f = SocketFactory.getDefault(); - try { - f.createSocket(InetAddress.getLocalHost(), 8081, InetAddress.getLocalHost(), 8082); - fail("IOException wasn't thrown ..."); - } catch (IOException expected) { - } - } - - /** - * javax.net.SocketFactory#createSocket(String host, int port, - * InetAddress localHost, int localPort) - */ - public final void test_createSocket_05() throws Exception { - SocketFactory sf = SocketFactory.getDefault(); - int sport = new ServerSocket(0).getLocalPort(); - int[] invalidPorts = {Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE}; - - Socket s = sf.createSocket(InetAddress.getLocalHost().getHostName(), sport, - InetAddress.getLocalHost(), 0); - assertNotNull(s); - assertTrue("1: Failed to create socket", s.getPort() == sport); - - try { - sf.createSocket("bla-bla", sport, InetAddress.getLocalHost(), 0); - fail("UnknownHostException wasn't thrown"); - } catch (UnknownHostException expected) { - } - - for (int i = 0; i < invalidPorts.length; i++) { - try { - sf.createSocket(InetAddress.getLocalHost().getHostName(), invalidPorts[i], - InetAddress.getLocalHost(), 0); - fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]); - } catch (IllegalArgumentException expected) { - } - try { - sf.createSocket(InetAddress.getLocalHost().getHostName(), sport, - InetAddress.getLocalHost(), invalidPorts[i]); - fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]); - } catch (IllegalArgumentException expected) { - } - } - - try { - sf.createSocket(InetAddress.getLocalHost().getHostName(), 8081, InetAddress.getLocalHost(), 8082); - fail("IOException wasn't thrown ..."); - } catch (IOException expected) { - } - } - - /** - * javax.net.SocketFactory#getDefault() - */ - public final void test_getDefault() { - SocketFactory sf = SocketFactory.getDefault(); - Socket s; - try { - s = sf.createSocket(InetAddress.getLocalHost().getHostName(), 8082); - s.close(); - } catch (IOException e) { - } - try { - s = sf.createSocket(InetAddress.getLocalHost().getHostName(), 8081, InetAddress.getLocalHost(), 8082); - s.close(); - } catch (IOException e) { - } - try { - s = sf.createSocket(InetAddress.getLocalHost(), 8081); - s.close(); - } catch (IOException e) { - } - try { - s = sf.createSocket(InetAddress.getLocalHost(), 8081, InetAddress.getLocalHost(), 8082); - s.close(); - } catch (IOException e) { - } - } -} - -class MySocketFactory extends SocketFactory { - - public MySocketFactory() { - super(); - } - - @Override - public Socket createSocket(String host, int port) throws IOException, UnknownHostException { - return null; - } - - @Override - public Socket createSocket(String host, int port, InetAddress localHost, int localPort) - throws IOException, UnknownHostException { - return null; - } - - @Override - public Socket createSocket(InetAddress host, int port) throws IOException { - return null; - } - - @Override - public Socket createSocket(InetAddress address, int port, - InetAddress localAddress, int localPort) throws IOException { - return null; - } - -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/CertPathTrustManagerParametersTest.java b/luni/src/test/java/tests/api/javax/net/ssl/CertPathTrustManagerParametersTest.java deleted file mode 100644 index 41407e8..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/CertPathTrustManagerParametersTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.net.ssl; - -import java.security.cert.CertPathParameters; -import javax.net.ssl.CertPathTrustManagerParameters; - -import junit.framework.TestCase; - -/** - * Tests for <code>CertPathTrustManagerParameters</code> class constructors - * and methods. - * - */ -public class CertPathTrustManagerParametersTest extends TestCase { - - /** - * javax.net.ssl.CertPathTrustManagerParameters# - * CertPathTrustManagerParameters(java.security.cert.CertPathParameters) - * Case 1: Try to construct object. - * Case 2: Check NullPointerException. - */ - public void test_ConstructorLjava_security_cert_CertPathParameters() { - // case 1: Try to construct object. - try { - CertPathParameters parameters = new MyCertPathParameters(); - CertPathTrustManagerParameters p = - new CertPathTrustManagerParameters(parameters); - assertNotSame("Parameters were cloned incorrectly", - parameters, p.getParameters()); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - - // case 2: Check NullPointerException. - try { - new CertPathTrustManagerParameters(null); - fail("Expected CertPathTrustManagerParameters was not thrown"); - } catch (NullPointerException npe) { - // expected - } - } - - /** - * javax.net.ssl.CertPathTrustManagerParameters#getParameters() - */ - public void test_getParameters() { - CertPathParameters parameters = new MyCertPathParameters(); - CertPathTrustManagerParameters p = new CertPathTrustManagerParameters( - parameters); - if (!(p.getParameters() instanceof MyCertPathParameters)) { - fail("incorrect parameters"); - } - assertNotSame("Parameters were cloned incorrectly", - parameters, p.getParameters()); - } -} - -class MyCertPathParameters implements CertPathParameters { - public Object clone() { - return new MyCertPathParameters(); - } -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/CertificatesToPlayWith.java b/luni/src/test/java/tests/api/javax/net/ssl/CertificatesToPlayWith.java deleted file mode 100644 index 5bb6f06..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/CertificatesToPlayWith.java +++ /dev/null @@ -1,478 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * <http://www.apache.org/>. - * - */ - -package tests.api.javax.net.ssl; - -/** - * Some X509 certificates to test against. - * <p/> - * Note: some of these certificates have Japanese Kanji in the "subjectAlt" - * field (UTF8). Not sure how realistic that is since international characters - * in DNS names usually get translated into ASCII using "xn--" style DNS - * entries. "xn--i8s592g.co.jp" is what FireFox actually uses when trying to - * find 花子.co.jp. So would the CN in the certificate contain - * "xn--i8s592g.co.jp" in ASCII, or "花子.co.jp" in UTF8? (Both?) - * - * @since 11-Dec-2006 - */ -public interface CertificatesToPlayWith { - - /** - * CN=foo.com - */ - public final static byte[] X509_FOO = ( - "-----BEGIN CERTIFICATE-----\n" + - "MIIERjCCAy6gAwIBAgIJAIz+EYMBU6aQMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" + - "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" + - "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" + - "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" + - "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzE0MVoXDTI4MTEwNTE1MzE0MVowgaQx\n" + - "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" + - "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" + - "cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n" + - "aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" + - "ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" + - "lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" + - "zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" + - "07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" + - "BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" + - "JTxpTKqym93whYk93l3ocEe55c0CAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgB\n" + - "hvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYE\n" + - "FJ8Ud78/OrbKOIJCSBYs2tDLXofYMB8GA1UdIwQYMBaAFHua2o+QmU5S0qzbswNS\n" + - "yoemDT4NMA0GCSqGSIb3DQEBBQUAA4IBAQC3jRmEya6sQCkmieULcvx8zz1euCk9\n" + - "fSez7BEtki8+dmfMXe3K7sH0lI8f4jJR0rbSCjpmCQLYmzC3NxBKeJOW0RcjNBpO\n" + - "c2JlGO9auXv2GDP4IYiXElLJ6VSqc8WvDikv0JmCCWm0Zga+bZbR/EWN5DeEtFdF\n" + - "815CLpJZNcYwiYwGy/CVQ7w2TnXlG+mraZOz+owr+cL6J/ZesbdEWfjoS1+cUEhE\n" + - "HwlNrAu8jlZ2UqSgskSWlhYdMTAP9CPHiUv9N7FcT58Itv/I4fKREINQYjDpvQcx\n" + - "SaTYb9dr5sB4WLNglk7zxDtM80H518VvihTcP7FHL+Gn6g4j5fkI98+S\n" + - "-----END CERTIFICATE-----\n").getBytes(); - - /** - * CN=花子.co.jp - */ - public final static byte[] X509_HANAKO = ( - "-----BEGIN CERTIFICATE-----\n" + - "MIIESzCCAzOgAwIBAgIJAIz+EYMBU6aTMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" + - "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" + - "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" + - "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" + - "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1NDIxNVoXDTI4MTEwNTE1NDIxNVowgakx\n" + - "CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n" + - "IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n" + - "cnRpZmljYXRlczEVMBMGA1UEAwwM6Iqx5a2QLmNvLmpwMSUwIwYJKoZIhvcNAQkB\n" + - "FhZqdWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A\n" + - "MIIBCgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjU\n" + - "g4pNjYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQc\n" + - "wHf0ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t\n" + - "7iu1JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAn\n" + - "AxK6q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArD\n" + - "qUYxqJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwG\n" + - "CWCGSAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNV\n" + - "HQ4EFgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLS\n" + - "rNuzA1LKh6YNPg0wDQYJKoZIhvcNAQEFBQADggEBALJ27i3okV/KvlDp6KMID3gd\n" + - "ITl68PyItzzx+SquF8gahMh016NX73z/oVZoVUNdftla8wPUB1GwIkAnGkhQ9LHK\n" + - "spBdbRiCj0gMmLCsX8SrjFvr7cYb2cK6J/fJe92l1tg/7Y4o7V/s4JBe/cy9U9w8\n" + - "a0ctuDmEBCgC784JMDtT67klRfr/2LlqWhlOEq7pUFxRLbhpquaAHSOjmIcWnVpw\n" + - "9BsO7qe46hidgn39hKh1WjKK2VcL/3YRsC4wUi0PBtFW6ScMCuMhgIRXSPU55Rae\n" + - "UIlOdPjjr1SUNWGId1rD7W16Scpwnknn310FNxFMHVI0GTGFkNdkilNCFJcIoRA=\n" + - "-----END CERTIFICATE-----\n").getBytes(); - - /** - * CN=foo.com, subjectAlt=bar.com - */ - public final static byte[] X509_FOO_BAR = ( - "-----BEGIN CERTIFICATE-----\n" + - "MIIEXDCCA0SgAwIBAgIJAIz+EYMBU6aRMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" + - "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" + - "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" + - "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" + - "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzYyOVoXDTI4MTEwNTE1MzYyOVowgaQx\n" + - "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" + - "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" + - "cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n" + - "aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" + - "ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" + - "lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" + - "zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" + - "07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" + - "BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" + - "JTxpTKqym93whYk93l3ocEe55c0CAwEAAaOBkDCBjTAJBgNVHRMEAjAAMCwGCWCG\n" + - "SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E\n" + - "FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz\n" + - "A1LKh6YNPg0wEgYDVR0RBAswCYIHYmFyLmNvbTANBgkqhkiG9w0BAQUFAAOCAQEA\n" + - "dQyprNZBmVnvuVWjV42sey/PTfkYShJwy1j0/jcFZR/ypZUovpiHGDO1DgL3Y3IP\n" + - "zVQ26uhUsSw6G0gGRiaBDe/0LUclXZoJzXX1qpS55OadxW73brziS0sxRgGrZE/d\n" + - "3g5kkio6IED47OP6wYnlmZ7EKP9cqjWwlnvHnnUcZ2SscoLNYs9rN9ccp8tuq2by\n" + - "88OyhKwGjJfhOudqfTNZcDzRHx4Fzm7UsVaycVw4uDmhEHJrAsmMPpj/+XRK9/42\n" + - "2xq+8bc6HojdtbCyug/fvBZvZqQXSmU8m8IVcMmWMz0ZQO8ee3QkBHMZfCy7P/kr\n" + - "VbWx/uETImUu+NZg22ewEw==\n" + - "-----END CERTIFICATE-----\n").getBytes(); - - /** - * CN=foo.com, subjectAlt=bar.com, subjectAlt=花子.co.jp - * (hanako.co.jp in kanji) - */ - public final static byte[] X509_FOO_BAR_HANAKO = ( - "-----BEGIN CERTIFICATE-----\n" + - "MIIEajCCA1KgAwIBAgIJAIz+EYMBU6aSMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" + - "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" + - "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" + - "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" + - "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzgxM1oXDTI4MTEwNTE1MzgxM1owgaQx\n" + - "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" + - "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" + - "cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n" + - "aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" + - "ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" + - "lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" + - "zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" + - "07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" + - "BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" + - "JTxpTKqym93whYk93l3ocEe55c0CAwEAAaOBnjCBmzAJBgNVHRMEAjAAMCwGCWCG\n" + - "SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E\n" + - "FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz\n" + - "A1LKh6YNPg0wIAYDVR0RBBkwF4IHYmFyLmNvbYIM6Iqx5a2QLmNvLmpwMA0GCSqG\n" + - "SIb3DQEBBQUAA4IBAQBeZs7ZIYyKtdnVxVvdLgwySEPOE4pBSXii7XYv0Q9QUvG/\n" + - "++gFGQh89HhABzA1mVUjH5dJTQqSLFvRfqTHqLpxSxSWqMHnvRM4cPBkIRp/XlMK\n" + - "PlXadYtJLPTgpbgvulA1ickC9EwlNYWnowZ4uxnfsMghW4HskBqaV+PnQ8Zvy3L0\n" + - "12c7Cg4mKKS5pb1HdRuiD2opZ+Hc77gRQLvtWNS8jQvd/iTbh6fuvTKfAOFoXw22\n" + - "sWIKHYrmhCIRshUNohGXv50m2o+1w9oWmQ6Dkq7lCjfXfUB4wIbggJjpyEtbNqBt\n" + - "j4MC2x5rfsLKKqToKmNE7pFEgqwe8//Aar1b+Qj+\n" + - "-----END CERTIFICATE-----\n").getBytes(); - - /** - * CN=*.foo.com - */ - public final static byte[] X509_WILD_FOO = ( - "-----BEGIN CERTIFICATE-----\n" + - "MIIESDCCAzCgAwIBAgIJAIz+EYMBU6aUMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" + - "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" + - "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" + - "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" + - "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTU1NVoXDTI4MTEwNTE2MTU1NVowgaYx\n" + - "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" + - "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" + - "cnRpZmljYXRlczESMBAGA1UEAxQJKi5mb28uY29tMSUwIwYJKoZIhvcNAQkBFhZq\n" + - "dWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" + - "CgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pN\n" + - "jYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0\n" + - "ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1\n" + - "JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6\n" + - "q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYx\n" + - "qJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwGCWCG\n" + - "SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E\n" + - "FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz\n" + - "A1LKh6YNPg0wDQYJKoZIhvcNAQEFBQADggEBAH0ipG6J561UKUfgkeW7GvYwW98B\n" + - "N1ZooWX+JEEZK7+Pf/96d3Ij0rw9ACfN4bpfnCq0VUNZVSYB+GthQ2zYuz7tf/UY\n" + - "A6nxVgR/IjG69BmsBl92uFO7JTNtHztuiPqBn59pt+vNx4yPvno7zmxsfI7jv0ww\n" + - "yfs+0FNm7FwdsC1k47GBSOaGw38kuIVWqXSAbL4EX9GkryGGOKGNh0qvAENCdRSB\n" + - "G9Z6tyMbmfRY+dLSh3a9JwoEcBUso6EWYBakLbq4nG/nvYdYvG9ehrnLVwZFL82e\n" + - "l3Q/RK95bnA6cuRClGusLad0e6bjkBzx/VQ3VarDEpAkTLUGVAa0CLXtnyc=\n" + - "-----END CERTIFICATE-----\n").getBytes(); - - /** - * CN=*.co.jp - */ - public final static byte[] X509_WILD_CO_JP = ( - "-----BEGIN CERTIFICATE-----\n" + - "MIIERjCCAy6gAwIBAgIJAIz+EYMBU6aVMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" + - "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" + - "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" + - "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" + - "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTYzMFoXDTI4MTEwNTE2MTYzMFowgaQx\n" + - "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" + - "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" + - "cnRpZmljYXRlczEQMA4GA1UEAxQHKi5jby5qcDElMCMGCSqGSIb3DQEJARYWanVs\n" + - "aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" + - "ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" + - "lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" + - "zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" + - "07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" + - "BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" + - "JTxpTKqym93whYk93l3ocEe55c0CAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgB\n" + - "hvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYE\n" + - "FJ8Ud78/OrbKOIJCSBYs2tDLXofYMB8GA1UdIwQYMBaAFHua2o+QmU5S0qzbswNS\n" + - "yoemDT4NMA0GCSqGSIb3DQEBBQUAA4IBAQA0sWglVlMx2zNGvUqFC73XtREwii53\n" + - "CfMM6mtf2+f3k/d8KXhLNySrg8RRlN11zgmpPaLtbdTLrmG4UdAHHYr8O4y2BBmE\n" + - "1cxNfGxxechgF8HX10QV4dkyzp6Z1cfwvCeMrT5G/V1pejago0ayXx+GPLbWlNeZ\n" + - "S+Kl0m3p+QplXujtwG5fYcIpaGpiYraBLx3Tadih39QN65CnAh/zRDhLCUzKyt9l\n" + - "UGPLEUDzRHMPHLnSqT1n5UU5UDRytbjJPXzF+l/+WZIsanefWLsxnkgAuZe/oMMF\n" + - "EJMryEzOjg4Tfuc5qM0EXoPcQ/JlheaxZ40p2IyHqbsWV4MRYuFH4bkM\n" + - "-----END CERTIFICATE-----\n").getBytes(); - - /** - * CN=*.foo.com, subjectAlt=*.bar.com, subjectAlt=*.花子.co.jp - * (*.hanako.co.jp in kanji) - */ - public final static byte[] X509_WILD_FOO_BAR_HANAKO = ( - "-----BEGIN CERTIFICATE-----\n" + - "MIIEcDCCA1igAwIBAgIJAIz+EYMBU6aWMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" + - "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" + - "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" + - "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" + - "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTczMVoXDTI4MTEwNTE2MTczMVowgaYx\n" + - "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" + - "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" + - "cnRpZmljYXRlczESMBAGA1UEAxQJKi5mb28uY29tMSUwIwYJKoZIhvcNAQkBFhZq\n" + - "dWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" + - "CgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pN\n" + - "jYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0\n" + - "ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1\n" + - "JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6\n" + - "q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYx\n" + - "qJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo4GiMIGfMAkGA1UdEwQCMAAwLAYJ\n" + - "YIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0GA1Ud\n" + - "DgQWBBSfFHe/Pzq2yjiCQkgWLNrQy16H2DAfBgNVHSMEGDAWgBR7mtqPkJlOUtKs\n" + - "27MDUsqHpg0+DTAkBgNVHREEHTAbggkqLmJhci5jb22CDiou6Iqx5a2QLmNvLmpw\n" + - "MA0GCSqGSIb3DQEBBQUAA4IBAQBobWC+D5/lx6YhX64CwZ26XLjxaE0S415ajbBq\n" + - "DK7lz+Rg7zOE3GsTAMi+ldUYnhyz0wDiXB8UwKXl0SDToB2Z4GOgqQjAqoMmrP0u\n" + - "WB6Y6dpkfd1qDRUzI120zPYgSdsXjHW9q2H77iV238hqIU7qCvEz+lfqqWEY504z\n" + - "hYNlknbUnR525ItosEVwXFBJTkZ3Yw8gg02c19yi8TAh5Li3Ad8XQmmSJMWBV4XK\n" + - "qFr0AIZKBlg6NZZFf/0dP9zcKhzSriW27bY0XfzA6GSiRDXrDjgXq6baRT6YwgIg\n" + - "pgJsDbJtZfHnV1nd3M6zOtQPm1TIQpNmMMMd/DPrGcUQerD3\n" + - "-----END CERTIFICATE-----\n").getBytes(); - - /** - * CN=foo.com, CN=bar.com, CN=花子.co.jp - */ - public final static byte[] X509_THREE_CNS_FOO_BAR_HANAKO = ( - "-----BEGIN CERTIFICATE-----\n" + - "MIIEbzCCA1egAwIBAgIJAIz+EYMBU6aXMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" + - "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" + - "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" + - "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" + - "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTk0NVoXDTI4MTEwNTE2MTk0NVowgc0x\n" + - "CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n" + - "IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n" + - "cnRpZmljYXRlczEQMA4GA1UEAwwHZm9vLmNvbTEQMA4GA1UEAwwHYmFyLmNvbTEV\n" + - "MBMGA1UEAwwM6Iqx5a2QLmNvLmpwMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" + - "ZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyGOv\n" + - "loI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pNjYGViGjg7zhf\n" + - "bjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0ZHLN6sD9m2uV\n" + - "Sp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1JVjTuE0pcBva\n" + - "h2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6q/wGqcZ3zvFB\n" + - "TcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYxqJUlPGlMqrKb\n" + - "3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQf\n" + - "Fh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUnxR3vz86\n" + - "tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuzA1LKh6YNPg0w\n" + - "DQYJKoZIhvcNAQEFBQADggEBAGuZb8ai1NO2j4v3y9TLZvd5s0vh5/TE7n7RX+8U\n" + - "y37OL5k7x9nt0mM1TyAKxlCcY+9h6frue8MemZIILSIvMrtzccqNz0V1WKgA+Orf\n" + - "uUrabmn+CxHF5gpy6g1Qs2IjVYWA5f7FROn/J+Ad8gJYc1azOWCLQqSyfpNRLSvY\n" + - "EriQFEV63XvkJ8JrG62b+2OT2lqT4OO07gSPetppdlSa8NBSKP6Aro9RIX1ZjUZQ\n" + - "SpQFCfo02NO0uNRDPUdJx2huycdNb+AXHaO7eXevDLJ+QnqImIzxWiY6zLOdzjjI\n" + - "VBMkLHmnP7SjGSQ3XA4ByrQOxfOUTyLyE7NuemhHppuQPxE=\n" + - "-----END CERTIFICATE-----\n").getBytes(); - - /** - * subjectAlt=foo.com - */ - public final static byte[] X509_NO_CNS_FOO = ( - "-----BEGIN CERTIFICATE-----\n" + - "MIIESjCCAzKgAwIBAgIJAIz+EYMBU6aYMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" + - "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" + - "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" + - "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" + - "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MjYxMFoXDTI4MTEwNTE2MjYxMFowgZIx\n" + - "CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n" + - "IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n" + - "cnRpZmljYXRlczElMCMGCSqGSIb3DQEJARYWanVsaXVzZGF2aWVzQGdtYWlsLmNv\n" + - "bTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMhjr5aCPoyp0R1iroWA\n" + - "fnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2BlYho4O84X244QrZTRl8kQbYt\n" + - "xnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRyzerA/ZtrlUqf+lKo0uWcocxe\n" + - "Rc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY07hNKXAb2odnVqgzcYiDkLV8\n" + - "ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8BqnGd87xQU3FVZI4tbtkB+Kz\n" + - "jD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiVJTxpTKqym93whYk93l3ocEe5\n" + - "5c0CAwEAAaOBkDCBjTAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NM\n" + - "IEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUnxR3vz86tso4gkJIFiza\n" + - "0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuzA1LKh6YNPg0wEgYDVR0RBAsw\n" + - "CYIHZm9vLmNvbTANBgkqhkiG9w0BAQUFAAOCAQEAjl78oMjzFdsMy6F1sGg/IkO8\n" + - "tF5yUgPgFYrs41yzAca7IQu6G9qtFDJz/7ehh/9HoG+oqCCIHPuIOmS7Sd0wnkyJ\n" + - "Y7Y04jVXIb3a6f6AgBkEFP1nOT0z6kjT7vkA5LJ2y3MiDcXuRNMSta5PYVnrX8aZ\n" + - "yiqVUNi40peuZ2R8mAUSBvWgD7z2qWhF8YgDb7wWaFjg53I36vWKn90ZEti3wNCw\n" + - "qAVqixM+J0qJmQStgAc53i2aTMvAQu3A3snvH/PHTBo+5UL72n9S1kZyNCsVf1Qo\n" + - "n8jKTiRriEM+fMFlcgQP284EBFzYHyCXFb9O/hMjK2+6mY9euMB1U1aFFzM/Bg==\n" + - "-----END CERTIFICATE-----\n").getBytes(); - - /** - * Intermediate CA for all of these. - */ - public final static byte[] X509_INTERMEDIATE_CA = ( - "-----BEGIN CERTIFICATE-----\n" + - "MIIEnDCCA4SgAwIBAgIJAJTNwZ6yNa5cMA0GCSqGSIb3DQEBBQUAMIGGMQswCQYD\n" + - "VQQGEwJDQTELMAkGA1UECBMCQkMxFjAUBgNVBAoTDXd3dy5jdWNiYy5jb20xFDAS\n" + - "BgNVBAsUC2NvbW1vbnNfc3NsMRUwEwYDVQQDFAxkZW1vX3Jvb3RfY2ExJTAjBgkq\n" + - "hkiG9w0BCQEWFmp1bGl1c2Rhdmllc0BnbWFpbC5jb20wHhcNMDYxMTA1MjE0OTMx\n" + - "WhcNMDcxMTA1MjE0OTMxWjCBojELMAkGA1UEBhMCQ0ExCzAJBgNVBAgTAkJDMRIw\n" + - "EAYDVQQHEwlWYW5jb3V2ZXIxFjAUBgNVBAoTDXd3dy5jdWNiYy5jb20xFDASBgNV\n" + - "BAsUC2NvbW1vbnNfc3NsMR0wGwYDVQQDFBRkZW1vX2ludGVybWVkaWF0ZV9jYTEl\n" + - "MCMGCSqGSIb3DQEJARYWanVsaXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZI\n" + - "hvcNAQEBBQADggEPADCCAQoCggEBAL0S4y3vUO0EM6lwqOEfK8fvrUprIbsikXaG\n" + - "XzejcZ+T3l2Dc7t8WtBfRf78i4JypMqJQSijrUicj3H6mOMIReKaXm6ls4hA5d8w\n" + - "Lhmgiqsz/kW+gA8SeWGWRN683BD/RbQmzOls6ynBvap9jZlthXWBrSIlPCQoBLXY\n" + - "KVaxGzbL4ezaq+XFMKMQSm2uKwVmHHQNbfmZlPsuendBVomb/ked53Ab9IH6dwwN\n" + - "qJH9WIrvIzIVEXWlpvQ5MCqozM7u1akU+G8cazr8theGPCaYkzoXnigWua4OjdpV\n" + - "9z5ZDknhfBzG1AjapdG07FIirwWWgIyZXqZSD96ikmLtwT29qnsCAwEAAaOB7jCB\n" + - "6zAdBgNVHQ4EFgQUe5raj5CZTlLSrNuzA1LKh6YNPg0wgbsGA1UdIwSBszCBsIAU\n" + - "rN8eFIvMiRFXXgDqKumS0/W2AhOhgYykgYkwgYYxCzAJBgNVBAYTAkNBMQswCQYD\n" + - "VQQIEwJCQzEWMBQGA1UEChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9u\n" + - "c19zc2wxFTATBgNVBAMUDGRlbW9fcm9vdF9jYTElMCMGCSqGSIb3DQEJARYWanVs\n" + - "aXVzZGF2aWVzQGdtYWlsLmNvbYIJAJTNwZ6yNa5bMAwGA1UdEwQFMAMBAf8wDQYJ\n" + - "KoZIhvcNAQEFBQADggEBAIB4KMZvHD20pdKajFtMBpL7X4W4soq6EeTtjml3NYa9\n" + - "Qc52bsQEGNccKY9afYSBIndaQvFdtmz6HdoN+B8TjYShw2KhyjtKimGLpWYoi1YF\n" + - "e4aHdmA/Gp5xk8pZzR18FmooxC9RqBux+NAM2iTFSLgDtGIIj4sg2rbn6Bb6ZlQT\n" + - "1rg6VucXCA1629lNfMeNcu7CBNmUKIdaxHR/YJQallE0KfGRiOIWPrPj/VNk0YA6\n" + - "XFg0ocjqXJ2/N0N9rWVshMUaXgOh7m4D/5zga5/nuxDU+PoToA6mQ4bV6eCYqZbh\n" + - "aa1kQYtR9B4ZiG6pB82qVc2dCqStOH2FAEWos2gAVkQ=\n" + - "-----END CERTIFICATE-----\n").getBytes(); - - /** - * Root CA for all of these. - */ - public final static byte[] X509_ROOT_CA = ( - "-----BEGIN CERTIFICATE-----\n" + - "MIIEgDCCA2igAwIBAgIJAJTNwZ6yNa5bMA0GCSqGSIb3DQEBBQUAMIGGMQswCQYD\n" + - "VQQGEwJDQTELMAkGA1UECBMCQkMxFjAUBgNVBAoTDXd3dy5jdWNiYy5jb20xFDAS\n" + - "BgNVBAsUC2NvbW1vbnNfc3NsMRUwEwYDVQQDFAxkZW1vX3Jvb3RfY2ExJTAjBgkq\n" + - "hkiG9w0BCQEWFmp1bGl1c2Rhdmllc0BnbWFpbC5jb20wHhcNMDYxMTA1MjEzNjQz\n" + - "WhcNMjYxMTA1MjEzNjQzWjCBhjELMAkGA1UEBhMCQ0ExCzAJBgNVBAgTAkJDMRYw\n" + - "FAYDVQQKEw13d3cuY3VjYmMuY29tMRQwEgYDVQQLFAtjb21tb25zX3NzbDEVMBMG\n" + - "A1UEAxQMZGVtb19yb290X2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZpZXNA\n" + - "Z21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv+OnocmJ\n" + - "79UeO2hlCwK+Cle5uZWnU6uwJl+08z5cvebb5tT64WL9+psDbfgUH/Gm9JsuxKTg\n" + - "w1tZO/4duIgnaLNSx4HoqaTjwigd/hR3TsoGEPXTCkz1ikgTCOEDvl+iMid6aOrd\n" + - "mViE8HhscxKZ+h5FE7oHZyuT6gFoiaIXhFq+xK2w4ZwDz9L+paiwqywyUJJMnh9U\n" + - "jKorY+nua81N0oxpIhHPspCanDU4neMzCzYOZyLR/LqV5xORvHcFY84GWMz5hI25\n" + - "JbgaWJsYKuCAvNsnQwVoqKPGa7x1fn7x6oGsXJaCVt8weUwIj2xwg1lxMhrNaisH\n" + - "EvKpEAEnGGwWKQIDAQABo4HuMIHrMB0GA1UdDgQWBBSs3x4Ui8yJEVdeAOoq6ZLT\n" + - "9bYCEzCBuwYDVR0jBIGzMIGwgBSs3x4Ui8yJEVdeAOoq6ZLT9bYCE6GBjKSBiTCB\n" + - "hjELMAkGA1UEBhMCQ0ExCzAJBgNVBAgTAkJDMRYwFAYDVQQKEw13d3cuY3VjYmMu\n" + - "Y29tMRQwEgYDVQQLFAtjb21tb25zX3NzbDEVMBMGA1UEAxQMZGVtb19yb290X2Nh\n" + - "MSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZpZXNAZ21haWwuY29tggkAlM3BnrI1\n" + - "rlswDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAlPl3/8h1LttR1svC\n" + - "S8RXbHpAWIT2BEDhGHUNjSmgDQNkE/itf/FCEXh0tlU4bYdtBSOHzflbnzOyIPId\n" + - "VZeSWs33V38xDFy6KoVg1gT8JxkLmE5S1vWkpsHIlpw/U6r7KD0Kx9FYx5AiXjw0\n" + - "lzz/zlVNuO2U09KIDwDPVG1mBzQiMiSWj1U1pM4KxINkWQwDy/fvu/I983s8lW5z\n" + - "hf2WuFNzQN3fcMK5dpBE9NVIu27oYuGYh2sak34v+7T700W2ooBB71qFXtm9P5rl\n" + - "Yp9RCEsg3KEEPNTtCBs8fROeXvLDrP0cmBIqwGYDuRNCxFDTOdjv6YGdA8nLOjaH\n" + - "2dDk0g==\n" + - "-----END CERTIFICATE-----\n").getBytes(); - - /** - * Below is the private key for all the server certificates above (but - * not the intermediate CA or the root CA). All of those server certs - * came from the same private key. - */ - public final static String RSA_PUBLIC_MODULUS = - "00c863af96823e8ca9d11d62ae85807e713204c1985a80a2747f7ac863c5" + - "8d82e8c1ecf9698298d4838a4d8d81958868e0ef385f6e3842b653465f24" + - "41b62dc671a1e204820fe67c82367f80cbcb52586a39bf965cf0141cc077" + - "f46472cdeac0fd9b6b954a9ffa52a8d2e59ca1cc5e45cefbd4a37c70f1f7" + - "9c7674ad5d07c78640672e94e31c4e6dee2bb52558d3b84d29701bda8767" + - "56a83371888390b57c8a5bc49a8356316ae9f1406a913729121621098a77" + - "713920270312baabfc06a9c677cef1414dc5559238b5bb6407e2b38c3f73" + - "cfc4020c901f0e3647474dca350e66c4e817c31c0ac3a94631a895253c69" + - "4caab29bddf085893dde5de87047b9e5cd"; - - public final static String RSA_PUBLIC_EXPONENT = "65537"; - - public final static String RSA_PRIVATE_EXPONENT = - "577abd3295553d0efd4d38c13b62a6d03fa7b7e40cce4f1d5071877d96c6" + - "7a39a63f0f7ab21a89db8acae45587b3ef251309a70f74dc1ac02bde68f3" + - "8ed658e54e685ed370a18c054449512ea66a2252ed36e82b565b5159ec83" + - "f23df40ae189550a183865b25fd77789e960f0d8cedcd72f32d7a66edb4b" + - "a0a2baf3fbeb6c7d75f56ef0af9a7cff1c8c7f297d72eae7982164e50a89" + - "d450698cf598d39343201094241d2d180a95882a7111e58f4a5bdbc5c125" + - "a967dd6ed9ec614c5853e88e4c71e8b682a7cf89cb1d82b6fe78cc865084" + - "c8c5dfbb50c939df2b839c977b0245bfa3615e0592b527b1013d5b675ecb" + - "44e6b355c1df581f50997175166eef39"; - - public final static String RSA_PRIME1 = - "00fe759c4f0ce8b763880215e82767e7a937297668f4e4b1e119c6b22a3c" + - "a2c7b06c547d88d0aa45f645d7d3aeadaf7f8bc594deae0978529592977c" + - "b1ff890f05033a9e9e15551cad9fbf9c41d12139ccd99c1c3ac7b2197eff" + - "350d236bb900c1440953b64956e0a058ef824a2e16894af175177c77dbe1" + - "fef7d8b532608d2513"; - - public final static String RSA_PRIME2 = - "00c99a45878737a4cf73f9896680b75487f1b669b7686a6ba07103856f31" + - "db668c2c440c44cdd116f708f631c37a9adf119f5b5cb58ffe3dc62e20af" + - "af72693d936dc6bb3c5194996468389c1f094079b81522e94572b4ad7d39" + - "529178e9b8ebaeb1f0fdd83b8731c5223f1dea125341d1d64917f6b1a6ae" + - "c18d320510d79f859f"; - - public final static String RSA_EXPONENT1 = - "029febf0d4cd41b7011c2465b4a259bd6118486464c247236f44a169d61e" + - "47b9062508f674508d5031003ceabc57e714e600d71b2c75d5443db2da52" + - "6bb45a374f0537c5a1aab3150764ce93cf386c84346a6bd01f6732e42075" + - "c7a0e9e78a9e73b934e7d871d0f75673820089e129a1604438edcbbeb4e2" + - "106467da112ce389"; - - public final static String RSA_EXPONENT2 = - "00827e76650c946afcd170038d32e1f8386ab00d6be78d830efe382e45d4" + - "7ad4bd04e6231ee22e66740efbf52838134932c9f8c460cdccdec58a1424" + - "4427859192fd6ab6c58b74e97941b0eaf577f2a11713af5e5952af3ae124" + - "9a9a892e98410dfa2628d9af668a43b5302fb7d496c9b2fec69f595292b6" + - "e997f079b0f6314eb7"; - - public final static String RSA_COEFFICIENT = - "00e6b62add350f1a2a8968903ff76c31cf703b0d7326c4a620aef01225b7" + - "1640b3f2ec375208c5f7299863f6005b7799b6e529bb1133c8435bf5fdb5" + - "a786f6cd8a19ee7094a384e6557c600a38845a0960ddbfd1df18d0af5740" + - "001853788f1b5ccbf9affb4c52c9d2efdb8aab0183d86735b32737fb4e79" + - "2b8a9c7d91c7d175ae"; - - /** - * cat cert.cnf - * [req] - * distinguished_name=distinguished_name - * req_extensions=req_extensions - * x509_extensions=x509_extensions - * [distinguished_name] - * [req_extensions] - * [x509_extensions] - * subjectAltName=DNS:localhost.localdomain,DNS:localhost,IP:127.0.0.1 - * - * $ openssl req -x509 -nodes -days 36500 -subj '/CN=localhost' -config ./cert.cnf \ - * -newkey rsa:512 -out cert.pem - */ - public final static byte[] X509_MULTIPLE_SUBJECT_ALT = ( - "-----BEGIN CERTIFICATE-----\n" + - "MIIBWDCCAQKgAwIBAgIJANS1EtICX2AZMA0GCSqGSIb3DQEBBQUAMBQxEjAQBgNV\n" + - "BAMTCWxvY2FsaG9zdDAgFw0xMjAxMDIxOTA4NThaGA8yMTExMTIwOTE5MDg1OFow\n" + - "FDESMBAGA1UEAxMJbG9jYWxob3N0MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAPpt\n" + - "atK8r4/hf4hSIs0os/BSlQLbRBaK9AfBReM4QdAklcQqe6CHsStKfI8pp0zs7Ptg\n" + - "PmMdpbttL0O7mUboBC8CAwEAAaM1MDMwMQYDVR0RBCowKIIVbG9jYWxob3N0Lmxv\n" + - "Y2FsZG9tYWlugglsb2NhbGhvc3SHBH8AAAEwDQYJKoZIhvcNAQEFBQADQQD0ntfL\n" + - "DCzOCv9Ma6Lv5o5jcYWVxvBSTsnt22hsJpWD1K7iY9lbkLwl0ivn73pG2evsAn9G\n" + - "X8YKH52fnHsCrhSD\n" + - "-----END CERTIFICATE-----").getBytes(); - -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/HandshakeCompletedEventTest.java b/luni/src/test/java/tests/api/javax/net/ssl/HandshakeCompletedEventTest.java deleted file mode 100644 index c075cea..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/HandshakeCompletedEventTest.java +++ /dev/null @@ -1,613 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.net.ssl; - -import dalvik.annotation.AndroidOnly; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.InetSocketAddress; -import java.security.KeyStore; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import javax.net.ssl.HandshakeCompletedEvent; -import javax.net.ssl.HandshakeCompletedListener; -import javax.net.ssl.KeyManager; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLPeerUnverifiedException; -import javax.net.ssl.SSLServerSocket; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; -import javax.security.cert.X509Certificate; -import junit.framework.TestCase; -import libcore.io.Base64; -import org.apache.harmony.xnet.tests.support.mySSLSession; - -/** - * Tests for <code>HandshakeCompletedEvent</code> class constructors and methods. - * - */ -public class HandshakeCompletedEventTest extends TestCase { - - private String certificate = "-----BEGIN CERTIFICATE-----\n" - + "MIICZTCCAdICBQL3AAC2MA0GCSqGSIb3DQEBAgUAMF8xCzAJBgNVBAYTAlVTMSAw\n" - + "HgYDVQQKExdSU0EgRGF0YSBTZWN1cml0eSwgSW5jLjEuMCwGA1UECxMlU2VjdXJl\n" - + "IFNlcnZlciBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw05NzAyMjAwMDAwMDBa\n" - + "Fw05ODAyMjAyMzU5NTlaMIGWMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZv\n" - + "cm5pYTESMBAGA1UEBxMJUGFsbyBBbHRvMR8wHQYDVQQKExZTdW4gTWljcm9zeXN0\n" - + "ZW1zLCBJbmMuMSEwHwYDVQQLExhUZXN0IGFuZCBFdmFsdWF0aW9uIE9ubHkxGjAY\n" - + "BgNVBAMTEWFyZ29uLmVuZy5zdW4uY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB\n" - + "iQKBgQCofmdY+PiUWN01FOzEewf+GaG+lFf132UpzATmYJkA4AEA/juW7jSi+LJk\n" - + "wJKi5GO4RyZoyimAL/5yIWDV6l1KlvxyKslr0REhMBaD/3Z3EsLTTEf5gVrQS6sT\n" - + "WMoSZAyzB39kFfsB6oUXNtV8+UKKxSxKbxvhQn267PeCz5VX2QIDAQABMA0GCSqG\n" - + "SIb3DQEBAgUAA34AXl3at6luiV/7I9MN5CXYoPJYI8Bcdc1hBagJvTMcmlqL2uOZ\n" - + "H9T5hNMEL9Tk6aI7yZPXcw/xI2K6pOR/FrMp0UwJmdxX7ljV6ZtUZf7pY492UqwC\n" - + "1777XQ9UEZyrKJvF5ntleeO0ayBqLGVKCWzWZX9YsXCpv47FNLZbupE=\n" - + "-----END CERTIFICATE-----\n"; - - - /** - * @throws IOException - * javax.net.ssl.HandshakeCompletedEvent#HandshakeCompletedEvent(SSLSocket sock, SSLSession s) - */ - public final void test_Constructor() throws Exception { - mySSLSession session = new mySSLSession(); - SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(); - HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session); - try { - new HandshakeCompletedEvent(null, null); - fail("Any exception wasn't thrown for null parameters"); - } catch (Exception expected) { - } - } - - /** - * @throws IOException - * javax.net.ssl.HandshakeCompletedEvent#getCipherSuite() - */ - public final void test_getCipherSuite() throws Exception { - mySSLSession session = new mySSLSession("localhost", 1080, null); - SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(); - HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session); - assertEquals("SuiteName", event.getCipherSuite()); - } - - /** - * @throws IOException - * javax.net.ssl.HandshakeCompletedEvent#getLocalCertificates() - */ - public final void test_getLocalCertificates() throws Exception { - mySSLSession session = new mySSLSession("localhost", 1080, null); - SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(); - HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session); - assertNull(event.getLocalCertificates()); - } - - /** - * @throws IOException - * javax.net.ssl.HandshakeCompletedEvent#getLocalPrincipal() - */ - public final void test_getLocalPrincipal() throws Exception { - mySSLSession session = new mySSLSession("localhost", 1080, null); - SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(); - HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session); - assertNull(event.getLocalPrincipal()); - } - - /** - * @throws IOException - * javax.net.ssl.HandshakeCompletedEvent#getPeerCertificateChain() - */ - public final void test_getPeerCertificateChain() throws Exception { - ByteArrayInputStream bis = new ByteArrayInputStream(certificate.getBytes()); - mySSLSession session = new mySSLSession((X509Certificate[]) null); - SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(); - HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session); - try { - event.getPeerCertificateChain(); - fail("SSLPeerUnverifiedException wasn't thrown"); - } catch (SSLPeerUnverifiedException expected) { - } - - X509Certificate xc = X509Certificate.getInstance(bis); - X509Certificate[] xcs = {xc}; - session = new mySSLSession(xcs); - event = new HandshakeCompletedEvent(socket, session); - - X509Certificate[] res = event.getPeerCertificateChain(); - assertEquals(1, res.length); - } - - /** - * @throws IOException - * javax.net.ssl.HandshakeCompletedEvent#getPeerCertificates() - */ - public final void test_getPeerCertificates() throws IOException { - mySSLSession session = new mySSLSession("localhost", 1080, null); - SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(); - HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session); - try { - event.getPeerCertificates(); - fail("SSLPeerUnverifiedException wasn't thrown"); - } catch (SSLPeerUnverifiedException expected) { - } - - session = new mySSLSession((X509Certificate[]) null); - event = new HandshakeCompletedEvent(socket, session); - Certificate[] res = event.getPeerCertificates(); - assertEquals(3, res.length); - } - - /** - * @throws IOException - * javax.net.ssl.HandshakeCompletedEvent#getPeerPrincipal() - */ - public final void test_getPeerPrincipal() throws IOException { - mySSLSession session = new mySSLSession("localhost", 1080, null); - SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(); - HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session); - assertNull(event.getPeerPrincipal()); - } - - /** - * @throws IOException - * javax.net.ssl.HandshakeCompletedEvent#getSession() - */ - public final void test_getSession() throws IOException { - mySSLSession session = new mySSLSession("localhost", 1080, null); - SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(); - HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session); - SSLSession ss = event.getSession(); - assertNotNull(ss); - assertEquals(session, ss); - } - - /** - * @throws IOException - * javax.net.ssl.HandshakeCompletedEvent#getSocket() - */ - public final void test_getSocket() throws IOException { - SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(); - HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, null); - SSLSocket ss = event.getSocket(); - assertNotNull(ss); - assertEquals(socket, ss); - } - - - // Regression test for CompletedHandshakeEvent not firing with a custom - // TrustManager - - - private SSLSocket socket; - private SSLServerSocket serverSocket; - private MyHandshakeListener listener; - private String host = "localhost"; - - private String PASSWORD = "android"; - - /** - * Defines the keystore contents for the server, BKS version. Holds just a - * single self-generated key. The subject name is "Test Server". - */ - private static final String SERVER_KEYS_BKS = - "AAAAAQAAABQDkebzoP1XwqyWKRCJEpn/t8dqIQAABDkEAAVteWtleQAAARpYl20nAAAAAQAFWC41" - + "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU1jANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET" - + "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV" - + "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMB4XDTA4MDYwNTExNTgxNFoXDTA4MDkw" - + "MzExNTgxNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U" - + "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IFNlcnZl" - + "cjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0LIdKaIr9/vsTq8BZlA3R+NFWRaH4lGsTAQy" - + "DPMF9ZqEDOaL6DJuu0colSBBBQ85hQTPa9m9nyJoN3pEi1hgamqOvQIWcXBk+SOpUGRZZFXwniJV" - + "zDKU5nE9MYgn2B9AoiH3CSuMz6HRqgVaqtppIe1jhukMc/kHVJvlKRNy9XMCAwEAATANBgkqhkiG" - + "9w0BAQUFAAOBgQC7yBmJ9O/eWDGtSH9BH0R3dh2NdST3W9hNZ8hIa8U8klhNHbUCSSktZmZkvbPU" - + "hse5LI3dh6RyNDuqDrbYwcqzKbFJaq/jX9kCoeb3vgbQElMRX8D2ID1vRjxwlALFISrtaN4VpWzV" - + "yeoHPW4xldeZmoVtjn8zXNzQhLuBqX2MmAAAAqwAAAAUvkUScfw9yCSmALruURNmtBai7kQAAAZx" - + "4Jmijxs/l8EBaleaUru6EOPioWkUAEVWCxjM/TxbGHOi2VMsQWqRr/DZ3wsDmtQgw3QTrUK666sR" - + "MBnbqdnyCyvM1J2V1xxLXPUeRBmR2CXorYGF9Dye7NkgVdfA+9g9L/0Au6Ugn+2Cj5leoIgkgApN" - + "vuEcZegFlNOUPVEs3SlBgUF1BY6OBM0UBHTPwGGxFBBcetcuMRbUnu65vyDG0pslT59qpaR0TMVs" - + "P+tcheEzhyjbfM32/vwhnL9dBEgM8qMt0sqF6itNOQU/F4WGkK2Cm2v4CYEyKYw325fEhzTXosck" - + "MhbqmcyLab8EPceWF3dweoUT76+jEZx8lV2dapR+CmczQI43tV9btsd1xiBbBHAKvymm9Ep9bPzM" - + "J0MQi+OtURL9Lxke/70/MRueqbPeUlOaGvANTmXQD2OnW7PISwJ9lpeLfTG0LcqkoqkbtLKQLYHI" - + "rQfV5j0j+wmvmpMxzjN3uvNajLa4zQ8l0Eok9SFaRr2RL0gN8Q2JegfOL4pUiHPsh64WWya2NB7f" - + "V+1s65eA5ospXYsShRjo046QhGTmymwXXzdzuxu8IlnTEont6P4+J+GsWk6cldGbl20hctuUKzyx" - + "OptjEPOKejV60iDCYGmHbCWAzQ8h5MILV82IclzNViZmzAapeeCnexhpXhWTs+xDEYSKEiG/camt" - + "bhmZc3BcyVJrW23PktSfpBQ6D8ZxoMfF0L7V2GQMaUg+3r7ucrx82kpqotjv0xHghNIm95aBr1Qw" - + "1gaEjsC/0wGmmBDg1dTDH+F1p9TInzr3EFuYD0YiQ7YlAHq3cPuyGoLXJ5dXYuSBfhDXJSeddUkl" - + "k1ufZyOOcskeInQge7jzaRfmKg3U94r+spMEvb0AzDQVOKvjjo1ivxMSgFRZaDb/4qw="; - - /** - * Defines the keystore contents for the server, JKS version. Holds just a - * single self-generated key. The subject name is "Test Server". - */ - private static final String SERVER_KEYS_JKS = - "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFfBeAAAArowggK2MA4GCisGAQQBKgIRAQEFAASC" - + "AqI2kp5XjnF8YZkhcF92YsJNQkvsmH7zqMM87j23zSoV4DwyE3XeC/gZWq1ToScIhoqZkzlbWcu4" - + "T/Zfc/DrfGk/rKbBL1uWKGZ8fMtlZk8KoAhxZk1JSyJvdkyKxqmzUbxk1OFMlN2VJNu97FPVH+du" - + "dvjTvmpdoM81INWBW/1fZJeQeDvn4mMbbe0IxgpiLnI9WSevlaDP/sm1X3iO9yEyzHLL+M5Erspo" - + "Cwa558fOu5DdsICMXhvDQxjWFKFhPHnKtGe+VvwkG9/bAaDgx3kfhk0w5zvdnkKb+8Ed9ylNRzdk" - + "ocAa/mxlMTOsTvDKXjjsBupNPIIj7OP4GNnZaxkJjSs98pEO67op1GX2qhy6FSOPNuq8k/65HzUc" - + "PYn6voEeh6vm02U/sjEnzRevQ2+2wXoAdp0EwtQ/DlMe+NvcwPGWKuMgX4A4L93DZGb04N2VmAU3" - + "YLOtZwTO0LbuWrcCM/q99G/7LcczkxIVrO2I/rh8RXVczlf9QzcrFObFv4ATuspWJ8xG7DhsMbnk" - + "rT94Pq6TogYeoz8o8ZMykesAqN6mt/9+ToIemmXv+e+KU1hI5oLwWMnUG6dXM6hIvrULY6o+QCPH" - + "172YQJMa+68HAeS+itBTAF4Clm/bLn6reHCGGU6vNdwU0lYldpiOj9cB3t+u2UuLo6tiFWjLf5Zs" - + "EQJETd4g/EK9nHxJn0GAKrWnTw7pEHQJ08elzUuy04C/jEEG+4QXU1InzS4o/kR0Sqz2WTGDoSoq" - + "ewuPRU5bzQs/b9daq3mXrnPtRBL6HfSDAdpTK76iHqLCGdqx3avHjVSBm4zFvEuYBCev+3iKOBmg" - + "yh7eQRTjz4UOWfy85omMBr7lK8PtfVBDzOXpasxS0uBgdUyBDX4tO6k9jZ8a1kmQRQAAAAEABVgu" - + "NTA5AAACSDCCAkQwggGtAgRIR8SKMA0GCSqGSIb3DQEBBAUAMGkxCzAJBgNVBAYTAlVTMRMwEQYD" - + "VQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzANBgNVBAoTBkdvb2dsZTEQMA4GA1UECxMH" - + "QW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBTZXJ2ZXIwHhcNMDgwNjA1MTA0ODQyWhcNMDgwOTAzMTA0" - + "ODQyWjBpMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8w" - + "DQYDVQQKEwZHb29nbGUxEDAOBgNVBAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMIGf" - + "MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwoC6chqCI84rj1PrXuJgbiit4EV909zR6N0jNlYfg" - + "itwB39bP39wH03rFm8T59b3mbSptnGmCIpLZn25KPPFsYD3JJ+wFlmiUdEP9H05flfwtFQJnw9uT" - + "3rRIdYVMPcQ3RoZzwAMliGr882I2thIDbA6xjGU/1nRIdvk0LtxH3QIDAQABMA0GCSqGSIb3DQEB" - + "BAUAA4GBAJn+6YgUlY18Ie+0+Vt8oEi81DNi/bfPrAUAh63fhhBikx/3R9dl3wh09Z6p7cIdNxjW" - + "n2ll+cRW9eqF7z75F0Omm0C7/KAEPjukVbszmzeU5VqzkpSt0j84YWi+TfcHRrfvhLbrlmGITVpY" - + "ol5pHLDyqGmDs53pgwipWqsn/nEXEBgj3EoqPeqHbDf7YaP8h/5BSt0="; - - /** - * Defines the keystore contents for the client, JKS version. Holds just a - * single self-generated key. The subject name is "Test Client". - */ - private static final String CLIENT_KEYS_JKS = - "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFhyMAAAArkwggK1MA4GCisGAQQBKgIRAQEFAASC" - + "AqGVSfXolBStZy4nnRNn4fAr+S7kfU2BS23wwW8uB2Ru3GvtLzlK9q08Gvq/LNqBafjyFTVL5FV5" - + "SED/8YomO5a98GpskSeRvytCiTBLJdgGhws5TOGekgIAcBROPGIyOtJPQ0HfOQs+BqgzGDHzHQhw" - + "u/8Tm6yQwiP+W/1I9B1QnaEztZA3mhTyMMJsmsFTYroGgAog885D5Cmzd8sYGfxec3R6I+xcmBAY" - + "eibR5kGpWwt1R+qMvRrtBqh5r6WSKhCBNax+SJVbtUNRiKyjKccdJg6fGqIWWeivwYTy0OhjA6b4" - + "NiZ/ZZs5pxFGWUj/Rlp0RYy8fCF6aw5/5s4Bf4MI6dPSqMG8Hf7sJR91GbcELyzPdM0h5lNavgit" - + "QPEzKeuDrGxhY1frJThBsNsS0gxeu+OgfJPEb/H4lpYX5IvuIGbWKcxoO9zq4/fimIZkdA8A+3eY" - + "mfDaowvy65NBVQPJSxaOyFhLHfeLqOeCsVENAea02vA7andZHTZehvcrqyKtm+z8ncHGRC2H9H8O" - + "jKwKHfxxrYY/jMAKLl00+PBb3kspO+BHI2EcQnQuMw/zr83OR9Meq4TJ0TMuNkApZELAeFckIBbS" - + "rBr8NNjAIfjuCTuKHhsTFWiHfk9ZIzigxXagfeDRiyVc6khOuF/bGorj23N2o7Rf3uLoU6PyXWi4" - + "uhctR1aL6NzxDoK2PbYCeA9hxbDv8emaVPIzlVwpPK3Ruvv9mkjcOhZ74J8bPK2fQmbplbOljcZi" - + "tZijOfzcO/11JrwhuJZRA6wanTqHoujgChV9EukVrmbWGGAcewFnAsSbFXIik7/+QznXaDIt5NgL" - + "H/Bcz4Z/fdV7Ae1eUaxKXdPbI//4J+8liVT/d8awjW2tldIaDlmGMR3aoc830+3mAAAAAQAFWC41" - + "MDkAAAJIMIICRDCCAa0CBEhHxLgwDQYJKoZIhvcNAQEEBQAwaTELMAkGA1UEBhMCVVMxEzARBgNV" - + "BAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01UVjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdB" - + "bmRyb2lkMRQwEgYDVQQDEwtUZXN0IENsaWVudDAeFw0wODA2MDUxMDQ5MjhaFw0wODA5MDMxMDQ5" - + "MjhaMGkxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzAN" - + "BgNVBAoTBkdvb2dsZTEQMA4GA1UECxMHQW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBDbGllbnQwgZ8w" - + "DQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAIK3Q+KiFbmCGg422TAo4gggdhMH6FJhiuz8DxRyeMKR" - + "UAfP4MK0wtc8N42waZ6OKvxpBFUy0BRfBsX0GD4Ku99yu9/tavSigTraeJtwV3WWRRjIqk7L3wX5" - + "cmgS2KSD43Y0rNUKrko26lnt9N4qiYRBSj+tcAN3Lx9+ptqk1LApAgMBAAEwDQYJKoZIhvcNAQEE" - + "BQADgYEANb7Q1GVSuy1RPJ0FmiXoMYCCtvlRLkmJphwxovK0cAQK12Vll+yAzBhHiQHy/RA11mng" - + "wYudC7u3P8X/tBT8GR1Yk7QW3KgFyPafp3lQBBCraSsfrjKj+dCLig1uBLUr4f68W8VFWZWWTHqp" - + "NMGpCX6qmjbkJQLVK/Yfo1ePaUexPSOX0G9m8+DoV3iyNw6at01NRw=="; - - /** - * Defines the keystore contents for the client, BKS version. Holds just a - * single self-generated key. The subject name is "Test Client". - */ - private static final String CLIENT_KEYS_BKS = - "AAAAAQAAABT4Rka6fxbFps98Y5k2VilmbibNkQAABfQEAAVteWtleQAAARpYl+POAAAAAQAFWC41" - + "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU9TANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET" - + "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV" - + "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgQ2xpZW50MB4XDTA4MDYwNTExNTg0NVoXDTA4MDkw" - + "MzExNTg0NVowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U" - + "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IENsaWVu" - + "dDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEApUvmWsQDHPpbDKK13Yez2/q54tTOmRml/qva" - + "2K6dZjkjSTW0iRuk7ztaVEvdJpfVIDv1oBsCI51ttyLHROy1epjF+GoL74mJb7fkcd0VOoSOTjtD" - + "+3GgZkHPAm5YmUYxiJXqxKKJJqMCTIW46eJaA2nAep9QIwZ14/NFAs4ObV8CAwEAATANBgkqhkiG" - + "9w0BAQUFAAOBgQCJrCr3hZQFDlLIfsSKI1/w+BLvyf4fubOid0pBxfklR8KBNPTiqjSmu7pd/C/F" - + "1FR8CdZUDoPflZHCOU+fj5r5KUC1HyigY/tEUvlforBpfB0uCF+tXW4DbUfOWhfMtLV4nCOJOOZg" - + "awfZLJWBJouLKOp427vDftxTSB+Ks8YjlgAAAqwAAAAU+NH6TtrzjyDdCXm5B6Vo7xX5G4YAAAZx" - + "EAUkcZtmykn7YdaYxC1jRFJ+GEJpC8nZVg83QClVuCSIS8a5f8Hl44Bk4oepOZsPzhtz3RdVzDVi" - + "RFfoyZFsrk9F5bDTVJ6sQbb/1nfJkLhZFXokka0vND5AXMSoD5Bj1Fqem3cK7fSUyqKvFoRKC3XD" - + "FQvhqoam29F1rbl8FaYdPvhhZo8TfZQYUyUKwW+RbR44M5iHPx+ykieMe/C/4bcM3z8cwIbYI1aO" - + "gjQKS2MK9bs17xaDzeAh4sBKrskFGrDe+2dgvrSKdoakJhLTNTBSG6m+rzqMSCeQpafLKMSjTSSz" - + "+KoQ9bLyax8cbvViGGju0SlVhquloZmKOfHr8TukIoV64h3uCGFOVFtQjCYDOq6NbfRvMh14UVF5" - + "zgDIGczoD9dMoULWxBmniGSntoNgZM+QP6Id7DBasZGKfrHIAw3lHBqcvB5smemSu7F4itRoa3D8" - + "N7hhUEKAc+xA+8NKmXfiCBoHfPHTwDvt4IR7gWjeP3Xv5vitcKQ/MAfO5RwfzkYCXQ3FfjfzmsE1" - + "1IfLRDiBj+lhQSulhRVStKI88Che3M4JUNGKllrc0nt1pWa1vgzmUhhC4LSdm6trTHgyJnB6OcS9" - + "t2furYjK88j1AuB4921oxMxRm8c4Crq8Pyuf+n3YKi8Pl2BzBtw++0gj0ODlgwut8SrVj66/nvIB" - + "jN3kLVahR8nZrEFF6vTTmyXi761pzq9yOVqI57wJGx8o3Ygox1p+pWUPl1hQR7rrhUbgK/Q5wno9" - + "uJk07h3IZnNxE+/IKgeMTP/H4+jmyT4mhsexJ2BFHeiKF1KT/FMcJdSi+ZK5yoNVcYuY8aZbx0Ef" - + "lHorCXAmLFB0W6Cz4KPP01nD9YBB4olxiK1t7m0AU9zscdivNiuUaB5OIEr+JuZ6dNw="; - - - /** - * Implements the actual test case. Launches a server and a client, requires - * client authentication and checks the certificates afterwards (not in the - * usual sense, we just make sure that we got the expected certificates, - * because our self-signed test certificates are not valid.) - */ - - @AndroidOnly("Uses bks key store. Change useBKS to false to run on the RI") - public void testClientAuth() throws Exception { - - boolean useBKS = true; - - listener = new MyHandshakeListener(); - String serverKeys = (useBKS ? SERVER_KEYS_BKS : SERVER_KEYS_JKS); - String clientKeys = (useBKS ? CLIENT_KEYS_BKS : CLIENT_KEYS_JKS); - TestServer server = new TestServer(true, - TestServer.CLIENT_AUTH_WANTED, serverKeys); - TestClient client = new TestClient(true, clientKeys); - - Thread serverThread = new Thread(server); - Thread clientThread = new Thread(client); - - serverThread.start(); - Thread.currentThread().sleep(3000); - clientThread.start(); - - serverThread.join(); - clientThread.join(); - - // The server must have completed without an exception. - Exception e = server.getException(); - if (e != null) { - e.printStackTrace(); - } - - // The client must have completed without an exception. - e = client.getException(); - if (e != null) { - e.printStackTrace(); - } - - assertNull(e); - - assertTrue(listener.completeDone); - } - - /** - * Implements a test SSL socket server. It wait for a connection on a given - * port, requests client authentication (if specified), reads 256 bytes - * from the socket, and writes 256 bytes to the socket. - */ - class TestServer implements Runnable { - - public static final int CLIENT_AUTH_NONE = 0; - - public static final int CLIENT_AUTH_WANTED = 1; - - public static final int CLIENT_AUTH_NEEDED = 2; - - private TestTrustManager trustManager; - - private Exception exception; - - String keys; - - private int clientAuth; - - private boolean provideKeys; - - public TestServer(boolean provideKeys, int clientAuth, String keys) throws Exception { - this.keys = keys; - this.clientAuth = clientAuth; - this.provideKeys = provideKeys; - - trustManager = new TestTrustManager(); - - KeyManager[] keyManagers = provideKeys ? getKeyManagers(keys) : null; - TrustManager[] trustManagers = new TrustManager[] { trustManager }; - - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyManagers, trustManagers, null); - - serverSocket = (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket(); - - if (clientAuth == CLIENT_AUTH_WANTED) { - serverSocket.setWantClientAuth(true); - } else if (clientAuth == CLIENT_AUTH_NEEDED) { - serverSocket.setNeedClientAuth(true); - } else { - serverSocket.setWantClientAuth(false); - } - - serverSocket.bind(new InetSocketAddress(0)); - } - - public void run() { - try { - SSLSocket clientSocket = (SSLSocket)serverSocket.accept(); - - InputStream istream = clientSocket.getInputStream(); - - for (int i = 0; i < 256; i++) { - int j = istream.read(); - assertEquals(i, j); - } - - istream.close(); - - OutputStream ostream = clientSocket.getOutputStream(); - - for (int i = 0; i < 256; i++) { - ostream.write(i); - } - - ostream.flush(); - ostream.close(); - - clientSocket.close(); - serverSocket.close(); - - } catch (Exception ex) { - exception = ex; - } - } - - public Exception getException() { - return exception; - } - - public X509Certificate[] getChain() { - return trustManager.getChain(); - } - - } - - /** - * Implements a test SSL socket client. It open a connection to localhost on - * a given port, writes 256 bytes to the socket, and reads 256 bytes from the - * socket. - */ - class TestClient implements Runnable { - - private TestTrustManager trustManager; - - private Exception exception; - - private String keys; - - private boolean provideKeys; - - public TestClient(boolean provideKeys, String keys) { - this.keys = keys; - this.provideKeys = provideKeys; - - trustManager = new TestTrustManager(); - } - - public void run() { - try { - KeyManager[] keyManagers = provideKeys ? getKeyManagers(keys) : null; - TrustManager[] trustManagers = new TrustManager[] { trustManager }; - - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyManagers, trustManagers, null); - - SSLSocket socket = (SSLSocket)sslContext.getSocketFactory().createSocket(); - - socket.connect(serverSocket.getLocalSocketAddress()); - socket.addHandshakeCompletedListener(listener); - socket.startHandshake(); - - OutputStream ostream = socket.getOutputStream(); - - for (int i = 0; i < 256; i++) { - ostream.write(i); - } - - ostream.flush(); - ostream.close(); - - InputStream istream = socket.getInputStream(); - - for (int i = 0; i < 256; i++) { - int j = istream.read(); - assertEquals(i, j); - } - - istream.close(); - - socket.close(); - - } catch (Exception ex) { - exception = ex; - } - } - - public Exception getException() { - return exception; - } - - public X509Certificate[] getChain() { - return trustManager.getChain(); - } - } - - /** - * Loads a keystore from a base64-encoded String. Returns the KeyManager[] - * for the result. - */ - private KeyManager[] getKeyManagers(String keys) throws Exception { - byte[] bytes = Base64.decode(keys.getBytes()); - InputStream inputStream = new ByteArrayInputStream(bytes); - - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(inputStream, PASSWORD.toCharArray()); - inputStream.close(); - - String algorithm = KeyManagerFactory.getDefaultAlgorithm(); - KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm); - keyManagerFactory.init(keyStore, PASSWORD.toCharArray()); - - return keyManagerFactory.getKeyManagers(); - } - - - /** - * Implements basically a dummy TrustManager. It stores the certificate - * chain it sees, so it can later be queried. - */ - public static class TestTrustManager implements X509TrustManager { - - private X509Certificate[] chain; - - private String authType; - - public void checkClientTrusted(X509Certificate[] chain, String authType) { - this.chain = chain; - this.authType = authType; - } - - public void checkServerTrusted(X509Certificate[] chain, String authType) { - this.chain = chain; - this.authType = authType; - } - - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return new java.security.cert.X509Certificate[0]; - } - - public X509Certificate[] getChain() { - return chain; - } - - public String getAuthType() { - return authType; - } - - public void checkClientTrusted( - java.security.cert.X509Certificate[] chain, String authType) - throws CertificateException { - - } - - public void checkServerTrusted( - java.security.cert.X509Certificate[] chain, String authType) - throws CertificateException { - - } - - } - - class MyHandshakeListener implements HandshakeCompletedListener { - - public boolean completeDone; - - MyHandshakeListener() { - completeDone = false; - } - - public void handshakeCompleted(HandshakeCompletedEvent event) { - if (event != null) completeDone = true; - } - } -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/HostnameVerifierTest.java b/luni/src/test/java/tests/api/javax/net/ssl/HostnameVerifierTest.java deleted file mode 100644 index 839f3b5..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/HostnameVerifierTest.java +++ /dev/null @@ -1,290 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with this - * work for additional information regarding copyright ownership. The ASF - * licenses this file to You 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 tests.api.javax.net.ssl; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.security.auth.x500.X500Principal; -import junit.framework.TestCase; -import org.apache.harmony.xnet.tests.support.mySSLSession; - -public class HostnameVerifierTest extends TestCase implements - CertificatesToPlayWith { - - /** - * javax.net.ssl.HostnameVerifier#verify(String hostname, SSLSession - * session) - */ - public final void test_verify() throws Exception { - mySSLSession session = new mySSLSession("localhost", 1080, null); - HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier(); - assertFalse(hv.verify("localhost", session)); - } - - // copied and modified from apache http client test suite. - public void testVerify() throws Exception { - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - InputStream in; - X509Certificate x509; - in = new ByteArrayInputStream(X509_FOO); - x509 = (X509Certificate) cf.generateCertificate(in); - mySSLSession session = new mySSLSession(new X509Certificate[] {x509}); - - HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier(); - assertTrue(verifier.verify("foo.com", session)); - assertFalse(verifier.verify("a.foo.com", session)); - assertFalse(verifier.verify("bar.com", session)); - - in = new ByteArrayInputStream(X509_HANAKO); - x509 = (X509Certificate) cf.generateCertificate(in); - session = new mySSLSession(new X509Certificate[] {x509}); - assertTrue(verifier.verify("\u82b1\u5b50.co.jp", session)); - assertFalse(verifier.verify("a.\u82b1\u5b50.co.jp", session)); - - in = new ByteArrayInputStream(X509_FOO_BAR); - x509 = (X509Certificate) cf.generateCertificate(in); - session = new mySSLSession(new X509Certificate[] {x509}); - assertFalse(verifier.verify("foo.com", session)); - assertFalse(verifier.verify("a.foo.com", session)); - assertTrue(verifier.verify("bar.com", session)); - assertFalse(verifier.verify("a.bar.com", session)); - - in = new ByteArrayInputStream(X509_FOO_BAR_HANAKO); - x509 = (X509Certificate) cf.generateCertificate(in); - session = new mySSLSession(new X509Certificate[] {x509}); - assertTrue(verifier.verify("foo.com", session)); - assertFalse(verifier.verify("a.foo.com", session)); - // these checks test alternative subjects. The test data contains an - // alternative subject starting with a japanese kanji character. This is - // not supported by Android because the underlying implementation from - // harmony follows the definition from rfc 1034 page 10 for alternative - // subject names. This causes the code to drop all alternative subjects. - // assertTrue(verifier.verify("bar.com", session)); - // assertFalse(verifier.verify("a.bar.com", session)); - // assertFalse(verifier.verify("a.\u82b1\u5b50.co.jp", session)); - - in = new ByteArrayInputStream(X509_NO_CNS_FOO); - x509 = (X509Certificate) cf.generateCertificate(in); - session = new mySSLSession(new X509Certificate[] {x509}); - assertTrue(verifier.verify("foo.com", session)); - assertFalse(verifier.verify("a.foo.com", session)); - - in = new ByteArrayInputStream(X509_NO_CNS_FOO); - x509 = (X509Certificate) cf.generateCertificate(in); - session = new mySSLSession(new X509Certificate[] {x509}); - assertTrue(verifier.verify("foo.com", session)); - assertFalse(verifier.verify("a.foo.com", session)); - - in = new ByteArrayInputStream(X509_THREE_CNS_FOO_BAR_HANAKO); - x509 = (X509Certificate) cf.generateCertificate(in); - session = new mySSLSession(new X509Certificate[] {x509}); - assertFalse(verifier.verify("foo.com", session)); - assertFalse(verifier.verify("a.foo.com", session)); - assertFalse(verifier.verify("bar.com", session)); - assertFalse(verifier.verify("a.bar.com", session)); - assertTrue(verifier.verify("\u82b1\u5b50.co.jp", session)); - assertFalse(verifier.verify("a.\u82b1\u5b50.co.jp", session)); - - in = new ByteArrayInputStream(X509_WILD_FOO); - x509 = (X509Certificate) cf.generateCertificate(in); - session = new mySSLSession(new X509Certificate[] {x509}); - assertTrue(verifier.verify("foo.com", session)); - assertTrue(verifier.verify("www.foo.com", session)); - assertTrue(verifier.verify("\u82b1\u5b50.foo.com", session)); - assertFalse(verifier.verify("a.b.foo.com", session)); - - in = new ByteArrayInputStream(X509_WILD_CO_JP); - x509 = (X509Certificate) cf.generateCertificate(in); - session = new mySSLSession(new X509Certificate[] {x509}); - assertTrue(verifier.verify("foo.co.jp", session)); - assertTrue(verifier.verify("\u82b1\u5b50.co.jp", session)); - - in = new ByteArrayInputStream(X509_WILD_FOO_BAR_HANAKO); - x509 = (X509Certificate) cf.generateCertificate(in); - session = new mySSLSession(new X509Certificate[] {x509}); - // try the foo.com variations - assertTrue(verifier.verify("foo.com", session)); - assertTrue(verifier.verify("www.foo.com", session)); - assertTrue(verifier.verify("\u82b1\u5b50.foo.com", session)); - assertFalse(verifier.verify("a.b.foo.com", session)); - // these checks test alternative subjects. The test data contains an - // alternative subject starting with a japanese kanji character. This is - // not supported by Android because the underlying implementation from - // harmony follows the definition from rfc 1034 page 10 for alternative - // subject names. This causes the code to drop all alternative subjects. - // assertFalse(verifier.verify("bar.com", session)); - // assertTrue(verifier.verify("www.bar.com", session)); - // assertTrue(verifier.verify("\u82b1\u5b50.bar.com", session)); - // assertTrue(verifier.verify("a.b.bar.com", session)); - } - - public void testSubjectAlt() throws Exception { - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - InputStream in = new ByteArrayInputStream(X509_MULTIPLE_SUBJECT_ALT); - X509Certificate x509 = (X509Certificate) cf.generateCertificate(in); - mySSLSession session = new mySSLSession(new X509Certificate[] {x509}); - - HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier(); - assertEquals(new X500Principal("CN=localhost"), x509.getSubjectX500Principal()); - - assertTrue(verifier.verify("localhost", session)); - assertTrue(verifier.verify("localhost.localdomain", session)); - assertFalse(verifier.verify("local.host", session)); - } - - public void testVerifyIpAddress() throws Exception { - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - InputStream in = new ByteArrayInputStream(X509_MULTIPLE_SUBJECT_ALT); - X509Certificate x509 = (X509Certificate) cf.generateCertificate(in); - mySSLSession session = new mySSLSession(new X509Certificate[] { x509 }); - HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier(); - - assertTrue(verifier.verify("127.0.0.1", session)); - assertFalse(verifier.verify("127.0.0.2", session)); - } - - public void testWildcardsCannotMatchIpAddresses() throws Exception { - // openssl req -x509 -nodes -days 36500 -subj '/CN=*.0.0.1' -newkey rsa:512 -out cert.pem - String cert = "-----BEGIN CERTIFICATE-----\n" - + "MIIBkjCCATygAwIBAgIJAMdemqOwd/BEMA0GCSqGSIb3DQEBBQUAMBIxEDAOBgNV\n" - + "BAMUByouMC4wLjEwIBcNMTAxMjIwMTY0NDI1WhgPMjExMDExMjYxNjQ0MjVaMBIx\n" - + "EDAOBgNVBAMUByouMC4wLjEwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAqY8c9Qrt\n" - + "YPWCvb7lclI+aDHM6fgbJcHsS9Zg8nUOh5dWrS7AgeA25wyaokFl4plBbbHQe2j+\n" - + "cCjsRiJIcQo9HwIDAQABo3MwcTAdBgNVHQ4EFgQUJ436TZPJvwCBKklZZqIvt1Yt\n" - + "JjEwQgYDVR0jBDswOYAUJ436TZPJvwCBKklZZqIvt1YtJjGhFqQUMBIxEDAOBgNV\n" - + "BAMUByouMC4wLjGCCQDHXpqjsHfwRDAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEB\n" - + "BQUAA0EAk9i88xdjWoewqvE+iMC9tD2obMchgFDaHH0ogxxiRaIKeEly3g0uGxIt\n" - + "fl2WRY8hb4x+zRrwsFaLEpdEvqcjOQ==\n" - + "-----END CERTIFICATE-----"; - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - InputStream in = new ByteArrayInputStream(cert.getBytes("UTF-8")); - X509Certificate x509 = (X509Certificate) cf.generateCertificate(in); - mySSLSession session = new mySSLSession(new X509Certificate[] { x509 }); - HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier(); - - assertFalse(verifier.verify("127.0.0.1", session)); - } - - /** - * Earlier implementations of Android's hostname verifier required that - * wildcard names wouldn't match "*.com" or similar. This was a nonstandard - * check that we've since dropped. It is the CA's responsibility to not hand - * out certificates that match so broadly. - */ - public void testWildcardsDoesNotNeedTwoDots() throws Exception { - // openssl req -x509 -nodes -days 36500 -subj '/CN=*.com' -newkey rsa:512 -out cert.pem - String cert = "-----BEGIN CERTIFICATE-----\n" - + "MIIBjDCCATagAwIBAgIJAOVulXCSu6HuMA0GCSqGSIb3DQEBBQUAMBAxDjAMBgNV\n" - + "BAMUBSouY29tMCAXDTEwMTIyMDE2NDkzOFoYDzIxMTAxMTI2MTY0OTM4WjAQMQ4w\n" - + "DAYDVQQDFAUqLmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDJd8xqni+h7Iaz\n" - + "ypItivs9kPuiJUqVz+SuJ1C05SFc3PmlRCvwSIfhyD67fHcbMdl+A/LrIjhhKZJe\n" - + "1joO0+pFAgMBAAGjcTBvMB0GA1UdDgQWBBS4Iuzf5w8JdCp+EtBfdFNudf6+YzBA\n" - + "BgNVHSMEOTA3gBS4Iuzf5w8JdCp+EtBfdFNudf6+Y6EUpBIwEDEOMAwGA1UEAxQF\n" - + "Ki5jb22CCQDlbpVwkruh7jAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA0EA\n" - + "U6LFxmZr31lFyis2/T68PpjAppc0DpNQuA2m/Y7oTHBDi55Fw6HVHCw3lucuWZ5d\n" - + "qUYo4ES548JdpQtcLrW2sA==\n" - + "-----END CERTIFICATE-----"; - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - InputStream in = new ByteArrayInputStream(cert.getBytes("UTF-8")); - X509Certificate x509 = (X509Certificate) cf.generateCertificate(in); - mySSLSession session = new mySSLSession(new X509Certificate[] { x509 }); - HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier(); - - assertTrue(verifier.verify("google.com", session)); - } - - public void testSubjectAltName() throws Exception { - /* - * $ cat ./cert.cnf - * [req] - * distinguished_name=distinguished_name - * req_extensions=req_extensions - * x509_extensions=x509_extensions - * [distinguished_name] - * [req_extensions] - * [x509_extensions] - * subjectAltName=DNS:bar.com,DNS:baz.com - * - * $ openssl req -x509 -nodes -days 36500 -subj '/CN=foo.com' -config ./cert.cnf \ - * -newkey rsa:512 -out cert.pem - */ - String cert = "-----BEGIN CERTIFICATE-----\n" - + "MIIBPTCB6KADAgECAgkA7zoHaaqNGHQwDQYJKoZIhvcNAQEFBQAwEjEQMA4GA1UE\n" - + "AxMHZm9vLmNvbTAgFw0xMDEyMjAxODM5MzZaGA8yMTEwMTEyNjE4MzkzNlowEjEQ\n" - + "MA4GA1UEAxMHZm9vLmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQC+gmoSxF+8\n" - + "hbV+rgRQqHIJd50216OWQJbU3BvdlPbca779NYO4+UZWTFdBM8BdQqs3H4B5Agvp\n" - + "y7HeSff1F7XRAgMBAAGjHzAdMBsGA1UdEQQUMBKCB2Jhci5jb22CB2Jhei5jb20w\n" - + "DQYJKoZIhvcNAQEFBQADQQBXpZZPOY2Dy1lGG81JTr8L4or9jpKacD7n51eS8iqI\n" - + "oTznPNuXHU5bFN0AAGX2ij47f/EahqTpo5RdS95P4sVm\n" - + "-----END CERTIFICATE-----"; - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - InputStream in = new ByteArrayInputStream(cert.getBytes("UTF-8")); - X509Certificate x509 = (X509Certificate) cf.generateCertificate(in); - mySSLSession session = new mySSLSession(new X509Certificate[] { x509 }); - HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier(); - - assertFalse(verifier.verify("foo.com", session)); - assertTrue(verifier.verify("bar.com", session)); - assertTrue(verifier.verify("baz.com", session)); - assertFalse(verifier.verify("a.foo.com", session)); - assertFalse(verifier.verify("quux.com", session)); - } - - public void testSubjectAltNameWithWildcard() throws Exception { - /* - * $ cat ./cert.cnf - * [req] - * distinguished_name=distinguished_name - * req_extensions=req_extensions - * x509_extensions=x509_extensions - * [distinguished_name] - * [req_extensions] - * [x509_extensions] - * subjectAltName=DNS:bar.com,DNS:*.baz.com - * - * $ openssl req -x509 -nodes -days 36500 -subj '/CN=foo.com' -config ./cert.cnf \ - * -newkey rsa:512 -out cert.pem - */ - String cert = "-----BEGIN CERTIFICATE-----\n" - + "MIIBPzCB6qADAgECAgkAnv/7Jv5r7pMwDQYJKoZIhvcNAQEFBQAwEjEQMA4GA1UE\n" - + "AxMHZm9vLmNvbTAgFw0xMDEyMjAxODQ2MDFaGA8yMTEwMTEyNjE4NDYwMVowEjEQ\n" - + "MA4GA1UEAxMHZm9vLmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDAz2YXnyog\n" - + "YdYLSFr/OEgSumtwqtZKJTB4wqTW/eKbBCEzxnyUMxWZIqUGu353PzwfOuWp2re3\n" - + "nvVV+QDYQlh9AgMBAAGjITAfMB0GA1UdEQQWMBSCB2Jhci5jb22CCSouYmF6LmNv\n" - + "bTANBgkqhkiG9w0BAQUFAANBAB8yrSl8zqy07i0SNYx2B/FnvQY734pxioaqFWfO\n" - + "Bqo1ZZl/9aPHEWIwBrxYNVB0SGu/kkbt/vxqOjzzrkXukmI=\n" - + "-----END CERTIFICATE-----"; - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - InputStream in = new ByteArrayInputStream(cert.getBytes("UTF-8")); - X509Certificate x509 = (X509Certificate) cf.generateCertificate(in); - mySSLSession session = new mySSLSession(new X509Certificate[] { x509 }); - HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier(); - - assertFalse(verifier.verify("foo.com", session)); - assertTrue(verifier.verify("bar.com", session)); - assertTrue(verifier.verify("a.baz.com", session)); - assertTrue(verifier.verify("baz.com", session)); - assertFalse(verifier.verify("a.foo.com", session)); - assertFalse(verifier.verify("a.bar.com", session)); - assertFalse(verifier.verify("quux.com", session)); - } -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/HttpsURLConnectionTest.java b/luni/src/test/java/tests/api/javax/net/ssl/HttpsURLConnectionTest.java deleted file mode 100644 index e2ebdbd..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/HttpsURLConnectionTest.java +++ /dev/null @@ -1,341 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.net.ssl; - -import java.io.ByteArrayInputStream; -import java.net.URL; -import java.security.Principal; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLPeerUnverifiedException; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocketFactory; - -import org.apache.harmony.security.tests.support.cert.TestUtils; - -import junit.framework.TestCase; - - - -/** - * Tests for <code>HttpsURLConnection</code> class constructors and methods. - * - */ -public class HttpsURLConnectionTest extends TestCase { - - /** - * javax.net.ssl.HttpsURLConnection#HttpsURLConnection(java_net_URL) - */ - public final void test_Constructor() throws Exception { - new MyHttpsURLConnection(new URL("https://www.fortify.net/")); - new MyHttpsURLConnection(null); - } - - /** - * javax.net.ssl.HttpsURLConnection#getCipherSuite() - */ - public final void test_getCipherSuite() throws Exception { - URL url = new URL("https://localhost:55555"); - HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); - try { - connection.getCipherSuite(); - fail("IllegalStateException wasn't thrown"); - } catch (IllegalStateException expected) { - } - - HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/")); - assertEquals("CipherSuite", con.getCipherSuite()); - } - - /** - * javax.net.ssl.HttpsURLConnection#getLocalCertificates() - */ - public final void test_getLocalCertificates() throws Exception { - URL url = new URL("https://localhost:55555"); - HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); - try { - connection.getLocalCertificates(); - fail("IllegalStateException wasn't thrown"); - } catch (IllegalStateException expected) { - } - - HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508"); - assertNull(con.getLocalCertificates()); - con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509"); - Certificate[] cert = con.getLocalCertificates(); - assertNotNull(cert); - assertEquals(1, cert.length); - } - - /** - * javax.net.ssl.HttpsURLConnection#getDefaultHostnameVerifier() - */ - public final void test_getDefaultHostnameVerifier() { - HostnameVerifier verifyer = - HttpsURLConnection.getDefaultHostnameVerifier(); - assertNotNull("Default hostname verifyer is null", verifyer); - } - - /** - * javax.net.ssl.HttpsURLConnection#getDefaultSSLSocketFactory() - */ - public final void test_getDefaultSSLSocketFactory() { - SSLSocketFactory sf = HttpsURLConnection.getDefaultSSLSocketFactory(); - if (!sf.equals(SSLSocketFactory.getDefault())) { - fail("incorrect DefaultSSLSocketFactory"); - } - } - - /** - * javax.net.ssl.HttpsURLConnection#getHostnameVerifier() - */ - public final void test_getHostnameVerifier() - throws Exception { - HttpsURLConnection con = new MyHttpsURLConnection( - new URL("https://www.fortify.net/")); - HostnameVerifier verifyer = con.getHostnameVerifier(); - assertNotNull("Hostname verifyer is null", verifyer); - assertEquals("Incorrect value of hostname verirfyer", - HttpsURLConnection.getDefaultHostnameVerifier(), verifyer); - } - - /** - * javax.net.ssl.HttpsURLConnection#getLocalPrincipal() - */ - public final void test_getLocalPrincipal() throws Exception { - URL url = new URL("https://localhost:55555"); - HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); - try { - connection.getLocalPrincipal(); - fail("IllegalStateException wasn't thrown"); - } catch (IllegalStateException expected) { - } - - HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508"); - assertNull(con.getLocalPrincipal()); - con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509"); - assertNotNull("Local principal is null", con.getLocalPrincipal()); - } - - /** - * javax.net.ssl.HttpsURLConnection#getPeerPrincipal() - */ - public final void test_getPeerPrincipal() throws Exception { - URL url = new URL("https://localhost:55555"); - HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); - try { - connection.getPeerPrincipal(); - fail("IllegalStateException wasn't thrown"); - } catch (IllegalStateException expected) { - } - HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508"); - try { - Principal p = con.getPeerPrincipal(); - fail("SSLPeerUnverifiedException wasn't thrown"); - } catch (SSLPeerUnverifiedException expected) { - } - - con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509"); - Principal p = con.getPeerPrincipal(); - assertNotNull(p); - } - - /** - * javax.net.ssl.HttpsURLConnection#getServerCertificates() - */ - public final void test_getServerCertificates() throws Exception { - URL url = new URL("https://localhost:55555"); - HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); - try { - connection.getServerCertificates(); - fail("IllegalStateException wasn't thrown"); - } catch (IllegalStateException expected) { - } - - HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508"); - try { - con.getServerCertificates(); - fail("SSLPeerUnverifiedException wasn't thrown"); - } catch (SSLPeerUnverifiedException expected) { - } - - con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509"); - Certificate[] cert = con.getServerCertificates(); - assertNotNull(cert); - assertEquals(1, cert.length); - } - - /** - * javax.net.ssl.HttpsURLConnection#getSSLSocketFactory() - */ - public final void test_getSSLSocketFactory() { - HttpsURLConnection con = new MyHttpsURLConnection(null); - SSLSocketFactory sf = con.getSSLSocketFactory(); - if (!sf.equals(SSLSocketFactory.getDefault())) { - fail("incorrect DefaultSSLSocketFactory"); - } - } - - /** - * javax.net.ssl.HttpsURLConnection#setDefaultHostnameVerifier() - */ - public final void test_setDefaultHostnameVerifier() { - try { - HttpsURLConnection.setDefaultHostnameVerifier(null); - fail("No expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - HostnameVerifier def = HttpsURLConnection.getDefaultHostnameVerifier(); - try { - myHostnameVerifier hnv = new myHostnameVerifier(); - HttpsURLConnection.setDefaultHostnameVerifier(hnv); - assertEquals(hnv, HttpsURLConnection.getDefaultHostnameVerifier()); - } finally { - HttpsURLConnection.setDefaultHostnameVerifier(def); - } - } - - /** - * javax.net.ssl.HttpsURLConnection#setHostnameVerifier() - */ - public final void test_setHostnameVerifier() { - HttpsURLConnection con = new MyHttpsURLConnection(null); - try { - con.setHostnameVerifier(null); - fail("No expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - myHostnameVerifier hnv = new myHostnameVerifier(); - con.setHostnameVerifier(hnv); - } - - /** - * javax.net.ssl.HttpsURLConnection#setDefaultSSLSocketFactory() - */ - public final void test_setDefaultSSLSocketFactory() { - try { - HttpsURLConnection.setDefaultSSLSocketFactory(null); - fail("No expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory - .getDefault(); - HttpsURLConnection.setDefaultSSLSocketFactory(ssf); - } - - /** - * javax.net.ssl.HttpsURLConnection#setSSLSocketFactory() - */ - public final void test_setSSLSocketFactory() { - HttpsURLConnection con = new MyHttpsURLConnection(null); - try { - con.setSSLSocketFactory(null); - fail("No expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory - .getDefault(); - con.setSSLSocketFactory(ssf); - } -} - -class MyHttpsURLConnection extends javax.net.ssl.HttpsURLConnection { - - private String typeDone; - - public MyHttpsURLConnection(URL url) { - super(url); - } - - public MyHttpsURLConnection(URL url, String type) { - super(url); - typeDone = type; - } - - /* - * @see javax.net.ssl.HttpsURLConnection#getCipherSuite() - */ - public String getCipherSuite() { - return "CipherSuite"; - } - - /* - * @see javax.net.ssl.HttpsURLConnection#getLocalCertificates() - */ - public Certificate[] getLocalCertificates() { - try { - CertificateFactory cf = CertificateFactory.getInstance(typeDone); - byte[] barr = TestUtils.getX509Certificate_v1(); - ByteArrayInputStream bis = new ByteArrayInputStream(barr); - Certificate cert = cf.generateCertificate(bis); - return new Certificate[] { cert }; - } catch (CertificateException se) { - return null; - } - } - - /* - * @see javax.net.ssl.HttpsURLConnection#getServerCertificates() - */ - public Certificate[] getServerCertificates() throws SSLPeerUnverifiedException { - try { - CertificateFactory cf = CertificateFactory.getInstance(typeDone); - byte[] barr = TestUtils.getX509Certificate_v3(); - ByteArrayInputStream bis = new ByteArrayInputStream(barr); - Certificate cert = cf.generateCertificate(bis); - return new Certificate[] { cert }; - } catch (CertificateException se) { - throw new SSLPeerUnverifiedException("No server's end-entity certificate"); - } - } - - /* - * @see java.net.HttpURLConnection#disconnect() - */ - public void disconnect() { - } - - /* - * @see java.net.HttpURLConnection#usingProxy() - */ - public boolean usingProxy() { - return false; - } - - public void connect() { - } - -} - -class myHostnameVerifier implements HostnameVerifier { - - myHostnameVerifier() { - } - - public boolean verify(String hostname, SSLSession session) { - if (hostname == session.getPeerHost()) { - return true; - } else return false; - } -} - diff --git a/luni/src/test/java/tests/api/javax/net/ssl/KeyManagerFactory1Test.java b/luni/src/test/java/tests/api/javax/net/ssl/KeyManagerFactory1Test.java deleted file mode 100644 index b369ed9..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/KeyManagerFactory1Test.java +++ /dev/null @@ -1,532 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.net.ssl; - -import java.io.IOException; -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.Security; -import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; - -import javax.net.ssl.KeyStoreBuilderParameters; -import javax.net.ssl.ManagerFactoryParameters; -import javax.net.ssl.KeyManager; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.KeyManagerFactorySpi; - -import org.apache.harmony.security.tests.support.SpiEngUtils; -import org.apache.harmony.xnet.tests.support.MyKeyManagerFactorySpi; - -import junit.framework.TestCase; - -/** - * Tests for <code>KeyManagerFactory</code> class constructors and methods. - * - */ -public class KeyManagerFactory1Test extends TestCase { - - private static final String srvKeyManagerFactory = "KeyManagerFactory"; - - private static String defaultAlgorithm = null; - - private static String defaultProviderName = null; - - private static Provider defaultProvider = null; - - private static boolean DEFSupported = false; - - private static final String NotSupportedMsg = "There is no suitable provider for KeyManagerFactory"; - - private static final String[] invalidValues = SpiEngUtils.invalidValues; - - private static String[] validValues = new String[3]; - static { - defaultAlgorithm = Security - .getProperty("ssl.KeyManagerFactory.algorithm"); - if (defaultAlgorithm != null) { - defaultProvider = SpiEngUtils.isSupport(defaultAlgorithm, - srvKeyManagerFactory); - DEFSupported = (defaultProvider != null); - defaultProviderName = (DEFSupported ? defaultProvider.getName() - : null); - validValues[0] = defaultAlgorithm; - validValues[1] = defaultAlgorithm.toUpperCase(); - validValues[2] = defaultAlgorithm.toLowerCase(); - } - } - - protected KeyManagerFactory[] createKMFac() { - if (!DEFSupported) { - fail(defaultAlgorithm + " algorithm is not supported"); - return null; - } - KeyManagerFactory[] kMF = new KeyManagerFactory[3]; - try { - kMF[0] = KeyManagerFactory.getInstance(defaultAlgorithm); - kMF[1] = KeyManagerFactory.getInstance(defaultAlgorithm, - defaultProvider); - kMF[2] = KeyManagerFactory.getInstance(defaultAlgorithm, - defaultProviderName); - return kMF; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - /** - * avax.net.ssl.KeyManagerFactory#getAlgorithm() - */ - public void test_getAlgorithm() - throws NoSuchAlgorithmException, NoSuchProviderException { - if (!DEFSupported) fail(NotSupportedMsg); - assertEquals("Incorrect algorithm", - defaultAlgorithm, - KeyManagerFactory - .getInstance(defaultAlgorithm).getAlgorithm()); - assertEquals("Incorrect algorithm", - defaultAlgorithm, - KeyManagerFactory - .getInstance(defaultAlgorithm, defaultProviderName) - .getAlgorithm()); - assertEquals("Incorrect algorithm", - defaultAlgorithm, - KeyManagerFactory.getInstance(defaultAlgorithm, defaultProvider) - .getAlgorithm()); - } - - /** - * Test for <code>getDefaultAlgorithm()</code> method - * Assertion: returns value which is specifoed in security property - */ - public void test_getDefaultAlgorithm() { - if (!DEFSupported) { - fail(NotSupportedMsg); - return; - } - String def = KeyManagerFactory.getDefaultAlgorithm(); - if (defaultAlgorithm == null) { - assertNull("DefaultAlgorithm must be null", def); - } else { - assertEquals("Invalid default algorithm", def, defaultAlgorithm); - } - String defA = "Proba.keymanagerfactory.defaul.type"; - Security.setProperty("ssl.KeyManagerFactory.algorithm", defA); - assertEquals("Incorrect defaultAlgorithm", - KeyManagerFactory.getDefaultAlgorithm(), defA); - if (def == null) { - def = ""; - } - Security.setProperty("ssl.KeyManagerFactory.algorithm", def); - assertEquals("Incorrect defaultAlgorithm", - KeyManagerFactory.getDefaultAlgorithm(), def); - } - - /** - * Test for <code>getInstance(String algorithm)</code> method - * Assertions: - * returns security property "ssl.KeyManagerFactory.algorithm"; - * returns instance of KeyManagerFactory - */ - public void test_getInstanceLjava_lang_String01() throws NoSuchAlgorithmException { - if (!DEFSupported) { - fail(NotSupportedMsg); - return; - } - KeyManagerFactory keyMF; - for (int i = 0; i < validValues.length; i++) { - keyMF = KeyManagerFactory.getInstance(validValues[i]); - assertNotNull("No KeyManagerFactory created", keyMF); - assertEquals("Invalid algorithm", keyMF.getAlgorithm(), - validValues[i]); - } - } - - /** - * Test for <code>getInstance(String algorithm)</code> method - * Assertion: - * throws NullPointerException when algorithm is null; - * throws NoSuchAlgorithmException when algorithm is not correct; - */ - public void test_getInstanceLjava_lang_String02() { - try { - KeyManagerFactory.getInstance(null); - fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null"); - } catch (NoSuchAlgorithmException e) { - } catch (NullPointerException e) { - } - for (int i = 0; i < invalidValues.length; i++) { - try { - KeyManagerFactory.getInstance(invalidValues[i]); - fail("NoSuchAlgorithmException was not thrown as expected for algorithm: " - .concat(invalidValues[i])); - } catch (NoSuchAlgorithmException e) { - } - } - } - - /** - * Test for <code>getInstance(String algorithm, String provider)</code> - * method - * Assertion: throws IllegalArgumentException when provider is null or empty - */ - public void test_getInstanceLjava_lang_StringLjava_lang_String01() throws NoSuchProviderException, - NoSuchAlgorithmException { - if (!DEFSupported) { - fail(NotSupportedMsg); - return; - } - String provider = null; - for (int i = 0; i < validValues.length; i++) { - try { - KeyManagerFactory.getInstance(validValues[i], provider); - fail("Expected IllegalArgumentException was not thrown for null provider"); - } catch (IllegalArgumentException e) { - } - try { - KeyManagerFactory.getInstance(validValues[i], ""); - fail("Expected IllegalArgumentException was not thrown for empty provider"); - } catch (IllegalArgumentException e) { - } - } - } - - /** - * Test for <code>getInstance(String algorithm, String provider)</code> - * method - * Assertion: - * throws NullPointerException when algorithm is null; - * throws NoSuchAlgorithmException when algorithm is not correct; - */ - public void test_getInstanceLjava_lang_StringLjava_lang_String02() throws NoSuchProviderException { - if (!DEFSupported) { - fail(NotSupportedMsg); - return; - } - try { - KeyManagerFactory.getInstance(null, defaultProviderName); - fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null"); - } catch (NoSuchAlgorithmException e) { - } catch (NullPointerException e) { - } - for (int i = 0; i < invalidValues.length; i++) { - try { - KeyManagerFactory.getInstance(invalidValues[i], - defaultProviderName); - fail("NoSuchAlgorithmException must be thrown (algorithm: " - .concat(invalidValues[i]).concat(")")); - } catch (NoSuchAlgorithmException e) { - } - } - } - - /** - * Test for <code>getInstance(String algorithm, String provider)</code> - * method - * Assertion: throws NoSuchProviderException when provider has - * invalid value - */ - public void test_getInstanceLjava_lang_StringLjava_lang_String03() - throws NoSuchAlgorithmException { - if (!DEFSupported) { - fail(NotSupportedMsg); - return; - } - for (int i = 0; i < validValues.length; i++) { - for (int j = 1; j < invalidValues.length; j++) { - try { - KeyManagerFactory.getInstance(validValues[i], - invalidValues[j]); - fail("NuSuchProviderException must be thrown (algorithm: " - + validValues[i] + " provider: " + invalidValues[j] - + ")"); - } catch (NoSuchProviderException e) { - } - } - } - } - - /** - * Test for <code>getInstance(String algorithm, String provider)</code> - * method Assertion: returns instance of KeyManagerFactory - */ - public void test_getInstanceLjava_lang_StringLjava_lang_String04() - throws NoSuchProviderException, - NoSuchAlgorithmException { - if (!DEFSupported) { - fail(NotSupportedMsg); - return; - } - KeyManagerFactory kMF; - for (int i = 0; i < validValues.length; i++) { - kMF = KeyManagerFactory.getInstance(validValues[i], - defaultProviderName); - assertNotNull("No KeyManagerFactory created", kMF); - assertEquals("Incorrect algorithm", kMF.getAlgorithm(), - validValues[i]); - assertEquals("Incorrect provider", kMF.getProvider().getName(), - defaultProviderName); - } - } - - /** - * Test for <code>getInstance(String algorithm, Provider provider)</code> - * method - * Assertion: throws IllegalArgumentException when provider is null - */ - public void test_getInstanceLjava_lang_StringLjava_security_Provider01() - throws NoSuchAlgorithmException { - if (!DEFSupported) { - fail(NotSupportedMsg); - return; - } - Provider provider = null; - for (int i = 0; i < validValues.length; i++) { - try { - KeyManagerFactory.getInstance(validValues[i], provider); - fail("Expected IllegalArgumentException was not thrown when provider is null"); - } catch (IllegalArgumentException e) { - } - } - } - - /** - * Test for <code>getInstance(String algorithm, Provider provider)</code> - * method - * Assertion: - * throws NullPointerException when algorithm is null; - * throws NoSuchAlgorithmException when algorithm is not correct; - */ - public void test_getInstanceLjava_lang_StringLjava_security_Provider02() { - if (!DEFSupported) { - fail(NotSupportedMsg); - return; - } - try { - KeyManagerFactory.getInstance(null, defaultProvider); - fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null"); - } catch (NoSuchAlgorithmException e) { - } catch (NullPointerException e) { - } - for (int i = 0; i < invalidValues.length; i++) { - try { - KeyManagerFactory - .getInstance(invalidValues[i], defaultProvider); - fail("Expected NuSuchAlgorithmException was not thrown"); - } catch (NoSuchAlgorithmException e) { - } - } - } - - /** - * Test for <code>getInstance(String algorithm, Provider provider)</code> - * method - * Assertion: returns instance of KeyManagerFactory - */ - public void test_getInstanceLjava_lang_StringLjava_security_Provider03() - throws NoSuchAlgorithmException, - IllegalArgumentException { - if (!DEFSupported) { - fail(NotSupportedMsg); - return; - } - KeyManagerFactory kMF; - for (int i = 0; i < validValues.length; i++) { - kMF = KeyManagerFactory - .getInstance(validValues[i], defaultProvider); - assertNotNull("No KeyManagerFactory created", kMF); - assertEquals(kMF.getAlgorithm(), validValues[i]); - assertEquals(kMF.getProvider(), defaultProvider); - } - } - - /** - * Test for <code>KeyManagerFactory</code> constructor - * Assertion: returns KeyManagerFactory object - */ - public void test_Constructor() throws NoSuchAlgorithmException { - if (!DEFSupported) { - fail(NotSupportedMsg); - return; - } - KeyManagerFactorySpi spi = new MyKeyManagerFactorySpi(); - KeyManagerFactory keyMF = new myKeyManagerFactory(spi, defaultProvider, - defaultAlgorithm); - assertEquals("Incorrect algorithm", keyMF.getAlgorithm(), - defaultAlgorithm); - assertEquals("Incorrect provider", keyMF.getProvider(), defaultProvider); - try { - keyMF.init(null, new char[1]); - fail("UnrecoverableKeyException must be thrown"); - } catch (UnrecoverableKeyException e) { - } catch (Exception e) { - fail("Unexpected: "+e.toString()+" was thrown"); - } - keyMF = new myKeyManagerFactory(null, null, null); - assertNull("Aalgorithm must be null", keyMF.getAlgorithm()); - assertNull("Provider must be null", keyMF.getProvider()); - try { - keyMF.getKeyManagers(); - } catch (NullPointerException e) { - } - } - - /** - * avax.net.ssl.KeyManagerFactory#getKeyManagers() - * @throws NoSuchAlgorithmException - * @throws KeyStoreException - * @throws IOException - * @throws CertificateException - * @throws UnrecoverableKeyException - */ - public void test_getKeyManagers() - throws Exception { - if (!DEFSupported) fail(NotSupportedMsg); - KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm); - char[] pass = "password".toCharArray(); - kmf.init(null, pass); - assertNotNull("Key manager array is null", kmf.getKeyManagers()); - assertEquals("Incorrect size of array", - 1, kmf.getKeyManagers().length); - } - - /** - * avax.net.ssl.KeyManagerFactory#getProvider() - */ - public void test_getProvider() - throws Exception { - if (!DEFSupported) fail(NotSupportedMsg); - assertEquals("Incorrect provider", - defaultProvider, - KeyManagerFactory - .getInstance(defaultAlgorithm).getProvider()); - assertEquals("Incorrect provider", - defaultProvider, - KeyManagerFactory - .getInstance(defaultAlgorithm, defaultProviderName) - .getProvider()); - assertEquals("Incorrect provider", - defaultProvider, - KeyManagerFactory.getInstance(defaultAlgorithm, defaultProvider) - .getProvider()); - } - - /** - * Test for <code>init(KeyStore keyStore, char[] password)</code> and - * <code>getKeyManagers()</code> - * Assertion: returns not empty KeyManager array - */ - public void test_initLjava_security_KeyStore$C() - throws NoSuchAlgorithmException, - KeyStoreException, UnrecoverableKeyException { - if (!DEFSupported) { - fail(NotSupportedMsg); - return; - } - KeyManagerFactory[] keyMF = createKMFac(); - assertNotNull("KeyManagerFactory object were not created", keyMF); - KeyStore ksNull = null; - KeyManager[] km; - for (int i = 0; i < keyMF.length; i++) { - keyMF[i].init(ksNull, new char[10]); - km = keyMF[i].getKeyManagers(); - assertNotNull("Result should not be null", km); - assertTrue("Length of result KeyManager array should not be 0", - (km.length > 0)); - } - KeyStore ks; - try { - ks = KeyStore.getInstance(KeyStore.getDefaultType()); - ks.load(null, null); - } catch (KeyStoreException e) { - fail(e.toString() + "default KeyStore type is not supported"); - return; - } catch (Exception e) { - fail("Unexpected: " + e.toString()); - return; - } - for (int i = 0; i < keyMF.length; i++) { - try { - keyMF[i].init(ks, new char[10]); - } catch (KeyStoreException e) { - } - km = keyMF[i].getKeyManagers(); - assertNotNull("Result has not be null", km); - assertTrue("Length of result KeyManager array should not be 0", - (km.length > 0)); - } - - } - - /** - * Test for <code>init(ManagerFactoryParameters params)</code> - * Assertion: - * throws InvalidAlgorithmParameterException when params is null - */ - public void test_initLjavax_net_ssl_ManagerFactoryParameters() - throws NoSuchAlgorithmException { - - if (!DEFSupported) { - fail(NotSupportedMsg); - return; - } - ManagerFactoryParameters par = null; - KeyManagerFactory[] keyMF = createKMFac(); - assertNotNull("KeyManagerFactory object were not created", keyMF); - for (int i = 0; i < keyMF.length; i++) { - try { - keyMF[i].init(par); - fail("InvalidAlgorithmParameterException must be thrown"); - } catch (InvalidAlgorithmParameterException e) { - } - } - - KeyStore.ProtectionParameter pp = new ProtectionParameterImpl(); - KeyStore.Builder bld = KeyStore.Builder.newInstance("testType", null, pp); - assertNotNull("Null object KeyStore.Builder", bld); - - try { - KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm); - KeyStoreBuilderParameters ksp = new KeyStoreBuilderParameters(bld); - assertNotNull(ksp.getParameters()); - kmf.init(ksp); - fail("InvalidAlgorithmParameterException must be thrown"); - } catch (InvalidAlgorithmParameterException e) { - } - } - -} - -/** - * Additional class for KeyManagerFactory constructor verification - */ -class myKeyManagerFactory extends KeyManagerFactory { - public myKeyManagerFactory(KeyManagerFactorySpi spi, Provider prov, - String alg) { - super(spi, prov, alg); - } -} - -class ProtectionParameterImpl implements KeyStore.ProtectionParameter { - ProtectionParameterImpl(){} -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/KeyManagerFactory2Test.java b/luni/src/test/java/tests/api/javax/net/ssl/KeyManagerFactory2Test.java deleted file mode 100644 index 3d44396..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/KeyManagerFactory2Test.java +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.net.ssl; - -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.Security; -import java.security.UnrecoverableKeyException; - -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.ManagerFactoryParameters; - -import org.apache.harmony.security.tests.support.SpiEngUtils; -import org.apache.harmony.xnet.tests.support.MyKeyManagerFactorySpi; -import junit.framework.TestCase; - -/** - * Tests for KeyManagerFactory class constructors and methods - * - */ -public class KeyManagerFactory2Test extends TestCase { - private static final String srvKeyManagerFactory = "KeyManagerFactory"; - - private static final String defaultAlg = "KeyMF"; - - private static final String KeyManagerFactoryProviderClass = "org.apache.harmony.xnet.tests.support.MyKeyManagerFactorySpi"; - - private static final String[] invalidValues = SpiEngUtils.invalidValues; - - private static final String[] validValues; - - static { - validValues = new String[4]; - validValues[0] = defaultAlg; - validValues[1] = defaultAlg.toLowerCase(); - validValues[2] = "Keymf"; - validValues[3] = "kEYMF"; - } - - Provider mProv; - - protected void setUp() throws Exception { - super.setUp(); - mProv = (new SpiEngUtils()).new MyProvider("MyKMFProvider", - "Provider for testing", srvKeyManagerFactory.concat(".") - .concat(defaultAlg), KeyManagerFactoryProviderClass); - Security.insertProviderAt(mProv, 2); - } - - /* - * @see TestCase#tearDown() - */ - protected void tearDown() throws Exception { - super.tearDown(); - Security.removeProvider(mProv.getName()); - } - - private void checkResult(KeyManagerFactory keyMF) - throws Exception { - KeyStore kStore = null; - ManagerFactoryParameters mfp = null; - - char[] pass = { 'a', 'b', 'c' }; - - try { - keyMF.init(kStore, null); - fail("KeyStoreException must be thrown"); - } catch (KeyStoreException e) { - } - try { - keyMF.init(kStore, pass); - fail("UnrecoverableKeyException must be thrown"); - } catch (UnrecoverableKeyException e) { - } - try { - keyMF.init(mfp); - fail("InvalidAlgorithmParameterException must be thrown"); - } catch (InvalidAlgorithmParameterException e) { - } - assertNull("getKeyManagers() should return null object", keyMF - .getKeyManagers()); - - try { - kStore = KeyStore.getInstance(KeyStore.getDefaultType()); - kStore.load(null, null); - } catch (KeyStoreException e) { - fail("default keystore is not supported"); - return; - } - keyMF.init(kStore, pass); - - mfp = new MyKeyManagerFactorySpi.Parameters(kStore, null); - try { - keyMF.init(mfp); - fail("InvalidAlgorithmParameterException must be thrown"); - } catch (InvalidAlgorithmParameterException e) { - } - mfp = new MyKeyManagerFactorySpi.Parameters(kStore, pass); - keyMF.init(mfp); - } - /** - * Test for <code>getInstance(String algorithm)</code> method - * Assertions: - * throws NullPointerException when algorithm is null; - * throws NoSuchAlgorithmException when algorithm is not correct; - * returns KeyManagerFactory object - */ - public void test_getInstanceLjava_lang_String() throws Exception { - try { - KeyManagerFactory.getInstance(null); - fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null"); - } catch (NoSuchAlgorithmException e) { - } catch (NullPointerException e) { - } - for (int i = 0; i < invalidValues.length; i++) { - try { - KeyManagerFactory.getInstance(invalidValues[i]); - fail("NoSuchAlgorithmException must be thrown (algorithm: " - .concat(invalidValues[i]).concat(")")); - } catch (NoSuchAlgorithmException e) { - } - } - KeyManagerFactory keyMF; - for (int i = 0; i < validValues.length; i++) { - keyMF = KeyManagerFactory.getInstance(validValues[i]); - assertEquals("Incorrect algorithm", keyMF.getAlgorithm(), - validValues[i]); - assertEquals("Incorrect provider", keyMF.getProvider(), mProv); - checkResult(keyMF); - } - } - - /** - * Test for <code>getInstance(String algorithm, String provider)</code> - * method - * Assertions: - * throws NullPointerException when algorithm is null; - * throws NoSuchAlgorithmException when algorithm is not correct; - * throws IllegalArgumentException when provider is null or empty; - * throws NoSuchProviderException when provider is available; - * returns KeyManagerFactory object - */ - public void test_getInstanceLjava_lang_StringLjava_lang_String() - throws Exception - { - try { - KeyManagerFactory.getInstance(null, mProv.getName()); - fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null"); - } catch (NoSuchAlgorithmException e) { - } catch (NullPointerException e) { - } - for (int i = 0; i < invalidValues.length; i++) { - try { - KeyManagerFactory - .getInstance(invalidValues[i], mProv.getName()); - fail("NoSuchAlgorithmException must be thrown (algorithm: " - .concat(invalidValues[i]).concat(")")); - } catch (NoSuchAlgorithmException e) { - } - } - String prov = null; - for (int i = 0; i < validValues.length; i++) { - try { - KeyManagerFactory.getInstance(validValues[i], prov); - fail("IllegalArgumentException must be thrown when provider is null (algorithm: " - .concat(invalidValues[i]).concat(")")); - } catch (IllegalArgumentException e) { - } - try { - KeyManagerFactory.getInstance(validValues[i], ""); - fail("IllegalArgumentException must be thrown when provider is empty (algorithm: " - .concat(invalidValues[i]).concat(")")); - } catch (IllegalArgumentException e) { - } - } - for (int i = 0; i < validValues.length; i++) { - for (int j = 1; j < invalidValues.length; j++) { - try { - KeyManagerFactory.getInstance(validValues[i], - invalidValues[j]); - fail("NoSuchProviderException must be thrown (algorithm: " - .concat(invalidValues[i]).concat(" provider: ") - .concat(invalidValues[j]).concat(")")); - } catch (NoSuchProviderException e) { - } - } - } - KeyManagerFactory keyMF; - for (int i = 0; i < validValues.length; i++) { - keyMF = KeyManagerFactory.getInstance(validValues[i], mProv - .getName()); - assertEquals("Incorrect algorithm", keyMF.getAlgorithm(), - validValues[i]); - assertEquals("Incorrect provider", keyMF.getProvider().getName(), - mProv.getName()); - checkResult(keyMF); - } - } - - /** - * Test for <code>getInstance(String algorithm, Provider provider)</code> - * method - * Assertions: - * throws NullPointerException when algorithm is null; - * throws NoSuchAlgorithmException when algorithm is not correct; - * throws IllegalArgumentException when provider is null; - * returns KeyManagerFactory object - */ - public void test_getInstanceLjava_lang_StringLjava_security_Provider() - throws Exception - { - try { - KeyManagerFactory.getInstance(null, mProv); - fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null"); - } catch (NoSuchAlgorithmException e) { - } catch (NullPointerException e) { - } - for (int i = 0; i < invalidValues.length; i++) { - try { - KeyManagerFactory.getInstance(invalidValues[i], mProv); - fail("NoSuchAlgorithmException must be thrown (algorithm: " - .concat(invalidValues[i]).concat(")")); - } catch (NoSuchAlgorithmException e) { - } - } - Provider prov = null; - for (int i = 0; i < validValues.length; i++) { - try { - KeyManagerFactory.getInstance(validValues[i], prov); - fail("IllegalArgumentException must be thrown when provider is null (algorithm: " - .concat(invalidValues[i]).concat(")")); - } catch (IllegalArgumentException e) { - } - } - KeyManagerFactory keyMF; - for (int i = 0; i < validValues.length; i++) { - keyMF = KeyManagerFactory.getInstance(validValues[i], mProv); - assertEquals("Incorrect algorithm", keyMF.getAlgorithm(), - validValues[i]); - assertEquals("Incorrect provider", keyMF.getProvider(), mProv); - checkResult(keyMF); - } - } -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/KeyManagerFactorySpiTest.java b/luni/src/test/java/tests/api/javax/net/ssl/KeyManagerFactorySpiTest.java deleted file mode 100644 index fd44fda..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/KeyManagerFactorySpiTest.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.javax.net.ssl; - -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; -import javax.net.ssl.KeyManager; -import javax.net.ssl.KeyManagerFactorySpi; -import javax.net.ssl.ManagerFactoryParameters; - -import junit.framework.TestCase; - -import org.apache.harmony.xnet.tests.support.KeyManagerFactorySpiImpl; - -public class KeyManagerFactorySpiTest extends TestCase { - - /** - * javax.net.ssl.KeyManagerFactorySpi#KeyManagerFactorySpi() - */ - public void test_Constructor() { - try { - KeyManagerFactorySpiImpl kmf = new KeyManagerFactorySpiImpl(); - assertTrue(kmf instanceof KeyManagerFactorySpi); - } catch (Exception e) { - fail("Unexpected Exception " + e.toString()); - } - } - - /** - * javax.net.ssl.KeyManagerFactorySpi#KengineInit(KeyStore ks, char[] password) - */ - public void test_engineInit_01() { - KeyManagerFactorySpiImpl kmf = new KeyManagerFactorySpiImpl(); - KeyStore ks; - char[] psw = "password".toCharArray(); - - try { - kmf.engineInit(null, null); - fail("NoSuchAlgorithmException wasn't thrown"); - } catch (NoSuchAlgorithmException kse) { - //expected - } catch (Exception e) { - fail(e + " was thrown instead of NoSuchAlgorithmException"); - } - - try { - kmf.engineInit(null, psw); - fail("KeyStoreException wasn't thrown"); - } catch (KeyStoreException uke) { - //expected - } catch (Exception e) { - fail(e + " was thrown instead of KeyStoreException"); - } - - try { - ks = KeyStore.getInstance(KeyStore.getDefaultType()); - kmf.engineInit(ks, null); - fail("UnrecoverableKeyException wasn't thrown"); - } catch (UnrecoverableKeyException uke) { - //expected - } catch (Exception e) { - fail(e + " was thrown instead of UnrecoverableKeyException"); - } - - try { - KeyStore kst = KeyStore.getInstance(KeyStore.getDefaultType()); - kst.load(null, null); - kmf.engineInit(kst, psw); - } catch (Exception e) { - fail("Unexpected exception " + e); - } - } - - /** - * javax.net.ssl.KeyManagerFactorySpi#KengineInit(ManagerFactoryParameters spec) - */ - public void test_engineInit_02() { - KeyManagerFactorySpiImpl kmf = new KeyManagerFactorySpiImpl(); - - try { - kmf.engineInit(null); - fail("InvalidAlgorithmParameterException wasn't thrown"); - } catch (InvalidAlgorithmParameterException iape) { - //expected - } catch (Exception e) { - fail(e + " was thrown instead of InvalidAlgorithmParameterException"); - } - - try { - char[] psw = "password".toCharArray(); - Parameters pr = new Parameters(psw); - kmf.engineInit(pr); - } catch (Exception e) { - fail(e + " unexpected exception was thrown"); - } - } - - /** - * javax.net.ssl.KeyManagerFactorySpi#engineGetKeyManagers() - */ - public void test_engineGetKeyManagers() { - KeyManagerFactorySpiImpl kmf = new KeyManagerFactorySpiImpl(); - - try { - KeyManager[] km = kmf.engineGetKeyManagers(); - fail("IllegalStateException wasn't thrown"); - } catch (IllegalStateException ise) { - //expected - } catch (Exception e) { - fail(e + " was thrown instead of IllegalStateException"); - } - - try { - char[] psw = "password".toCharArray(); - Parameters pr = new Parameters(psw); - kmf.engineInit(pr); - KeyManager[] km = kmf.engineGetKeyManagers(); - assertNull("Object is not NULL", km); - } catch (Exception e) { - fail(e + " unexpected exception was thrown"); - } - } - - public class Parameters implements ManagerFactoryParameters { - private char[] passWD; - - public Parameters (char[] pass) { - this.passWD = pass; - } - public char[] getPassword() { - return passWD; - } - } - -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/KeyStoreBuilderParametersTest.java b/luni/src/test/java/tests/api/javax/net/ssl/KeyStoreBuilderParametersTest.java deleted file mode 100644 index a2fe49c..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/KeyStoreBuilderParametersTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.javax.net.ssl; - -import javax.net.ssl.KeyManagerFactorySpi; -import javax.net.ssl.KeyStoreBuilderParameters; -import java.security.KeyStore; -import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; - -public class KeyStoreBuilderParametersTest extends TestCase { - - /** - * javax.net.ssl.KeyStoreBuilderParameters#KeyStoreBuilderParameters(KeyStore.Builder builder) - */ - public void test_Constructor01() { - // Null parameter - try { - new KeyStoreBuilderParameters((KeyStore.Builder) null); - fail(); - } catch (NullPointerException expected) { - } - - // Not null parameter - KeyStore.ProtectionParameter pp = new ProtectionParameterImpl(); - KeyStore.Builder bld = KeyStore.Builder.newInstance("testType", null, pp); - assertNotNull("Null object KeyStore.Builder", bld); - KeyStoreBuilderParameters ksp = new KeyStoreBuilderParameters(bld); - assertNotNull(ksp.getParameters()); - } - - /** - * javax.net.ssl.KeyStoreBuilderParameters#KeyStoreBuilderParameters(List parameters) - */ - public void test_Constructor02() { - - // Null parameter - try { - KeyStoreBuilderParameters ksp = new KeyStoreBuilderParameters((List) null); - fail(); - } catch (NullPointerException expected) { - } - - // Empty parameter - List lsEmpty = new ArrayList<String>(); - try { - KeyStoreBuilderParameters ksp = new KeyStoreBuilderParameters(lsEmpty); - fail(); - } catch (IllegalArgumentException expected) { - } - - // Not null parameter - List lsFiled = new ArrayList<String>(); - lsFiled.add("Parameter1"); - lsFiled.add("Parameter2"); - new KeyStoreBuilderParameters(lsFiled); - } - - /** - * javax.net.ssl.KeyStoreBuilderParameters#getParameters() - */ - public void test_getParameters() { - String[] param = {"Parameter1", "Parameter2", "Parameter3"}; - List ls = new ArrayList<String>(); - for (int i = 0; i < param.length; i++) { - ls.add(param[i]); - } - KeyStoreBuilderParameters ksp = new KeyStoreBuilderParameters(ls); - List res_list = ksp.getParameters(); - try { - res_list.add("test"); - fail(); - } catch (UnsupportedOperationException expected) { - } - Object[] res = res_list.toArray(); - assertEquals(res.length, param.length); - for (int i = 0; i < res.length; i++) { - assertEquals(param[i], res[i]); - } - } - - private static class ProtectionParameterImpl implements KeyStore.ProtectionParameter { - private ProtectionParameterImpl() {} - } -} - diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLContext1Test.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLContext1Test.java deleted file mode 100644 index ee51cc0..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/SSLContext1Test.java +++ /dev/null @@ -1,599 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.net.ssl; - -import java.io.FileNotFoundException; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.SecureRandom; -import java.security.UnrecoverableKeyException; - -import javax.net.ssl.KeyManager; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLContextSpi; -import javax.net.ssl.SSLEngine; -import javax.net.ssl.SSLServerSocketFactory; -import javax.net.ssl.SSLSessionContext; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; - -import junit.framework.TestCase; - -import org.apache.harmony.security.tests.support.SpiEngUtils; -import org.apache.harmony.xnet.tests.support.MySSLContextSpi; - -/** - * Tests for <code>SSLContext</code> class constructors and methods. - * - */ -public class SSLContext1Test extends TestCase { - - private static String srvSSLContext = "SSLContext"; - public static String defaultProtocol = "TLS"; - private static final String NotSupportMsg = "Default protocol is not supported"; - private static String defaultProviderName = null; - private static Provider defaultProvider = null; - private static final String[] invalidValues = SpiEngUtils.invalidValues; - private static boolean DEFSupported = false; - private static String[] validValues = new String[3]; - static { - defaultProvider = SpiEngUtils.isSupport(defaultProtocol, srvSSLContext); - DEFSupported = (defaultProvider != null); - if (DEFSupported) { - defaultProviderName = (DEFSupported ? defaultProvider.getName() - : null); - validValues[0] = defaultProtocol; - validValues[1] = defaultProtocol.toUpperCase(); - validValues[2] = defaultProtocol.toLowerCase(); - } else { - defaultProtocol = null; - } - } - - protected SSLContext[] createSSLCon() { - if (!DEFSupported) { - fail(defaultProtocol + " protocol is not supported"); - return null; - } - SSLContext[] sslC = new SSLContext[3]; - try { - sslC[0] = SSLContext.getInstance(defaultProtocol); - sslC[1] = SSLContext.getInstance(defaultProtocol, defaultProvider); - sslC[2] = SSLContext.getInstance(defaultProtocol, - defaultProviderName); - return sslC; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - /** - * Test for <code>SSLContext</code> constructor Assertion: returns - * SSLContext object - */ - public void test_ConstructorLjavax_net_ssl_SSLContextSpiLjava_security_ProviderLjava_lang_String() - throws NoSuchAlgorithmException, - KeyManagementException { - if (!DEFSupported) { - fail(NotSupportMsg); - return; - } - SSLContextSpi spi = new MySSLContextSpi(); - SSLContext sslContext = new MySslContext(spi, defaultProvider, - defaultProtocol); - assertEquals("Incorrect protocol", defaultProtocol, - sslContext.getProtocol()); - assertEquals("Incorrect provider", defaultProvider, - sslContext.getProvider()); - TrustManager[] tm = null; - KeyManager[] km = null; - sslContext.init(km, tm, new SecureRandom()); - assertNotNull("No SSLEngine created", - sslContext.createSSLEngine()); - assertNotNull("No SSLEngine created", - sslContext.createSSLEngine("host", 8888)); - try { - sslContext.init(km, tm, null); - fail("KeyManagementException should be thrown for null " - + "SecureRandom"); - } catch (KeyManagementException e) { - } - - sslContext = new MySslContext(null, null, null); - assertNull("Incorrect protocol", sslContext.getProtocol()); - assertNull("Incorrect provider", sslContext.getProvider()); - try { - sslContext.createSSLEngine(); - fail("NullPointerException should be thrown"); - } catch (NullPointerException e) { - } - try { - sslContext.getSocketFactory(); - fail("NullPointerException should be thrown"); - } catch (NullPointerException e) { - } - } - - /** - * @throws KeyManagementException - * javax.net.ssl.SSLContext#createSSLEngine() - */ - public void test_createSSLEngine() throws KeyManagementException { - if (!DEFSupported) fail(NotSupportMsg); - SSLContextSpi spi = new MySSLContextSpi(); - SSLContext sslContext = new MySslContext(spi, defaultProvider, - defaultProtocol); - sslContext.init(null, null, new SecureRandom()); - SSLEngine sslEngine = sslContext.createSSLEngine(); - assertNotNull("SSL engine is null", sslEngine); - } - - /** - * @throws KeyManagementException - * javax.net.ssl.SSLContext#createSSLEngine(java.lang.String, int) - */ - public void test_createSSLEngineLjava_lang_StringI() - throws KeyManagementException { - if (!DEFSupported) fail(NotSupportMsg); - SSLContextSpi spi = new MySSLContextSpi(); - SSLContext sslContext = new MySslContext(spi, defaultProvider, - defaultProtocol); - sslContext.init(null, null, new SecureRandom()); - SSLEngine sslEngine = sslContext.createSSLEngine("www.fortify.net", 80); - assertNotNull("SSL engine is null", sslEngine); - } - - /** - * Test for <code>getClientSessionContext()</code> - * <code>getServiceSessionContext()</code> - * methods Assertion: returns correspondent object - * @throws KeyManagementException - */ - public void test_getClientSessionContext() throws NoSuchAlgorithmException, KeyManagementException { - if (!DEFSupported) { - fail(NotSupportMsg); - return; - } - SSLContext[] sslC = createSSLCon(); - assertNotNull("SSLContext objects were not created", sslC); - for (int i = 0; i < sslC.length; i++) { - sslC[i].init(null, null, null); - assertNotNull("Client session is incorrectly instantiated: " + i, - sslC[i].getClientSessionContext()); - assertNotNull("Server session is incorrectly instantiated: " + i, - sslC[i].getServerSessionContext()); - } - } - - /** - * Test for <code>getInstance(String protocol)</code> method Assertion: - * returns SSLContext object - */ - public void test_getInstanceLjava_lang_String01() - throws NoSuchAlgorithmException { - if (!DEFSupported) { - fail(NotSupportMsg); - return; - } - SSLContext sslContext; - for (int i = 0; i < validValues.length; i++) { - sslContext = SSLContext.getInstance(validValues[i]); - assertNotNull("No SSLContext created", sslContext); - assertEquals("Invalid protocol", validValues[i], - sslContext.getProtocol()); - } - } - - /** - * Test for <code>getInstance(String protocol)</code> method Assertion: - * throws NullPointerException when protocol is null; throws - * NoSuchAlgorithmException when protocol is not correct; - */ - public void test_getInstanceLjava_lang_String02() { - try { - SSLContext.getInstance(null); - fail("NoSuchAlgorithmException or NullPointerException should be thrown (protocol is null"); - } catch (NoSuchAlgorithmException e) { - } catch (NullPointerException e) { - } - for (int i = 0; i < invalidValues.length; i++) { - try { - SSLContext.getInstance(invalidValues[i]); - fail("NoSuchAlgorithmException was not thrown as expected for provider: " - .concat(invalidValues[i])); - } catch (NoSuchAlgorithmException e) { - } - } - } - - /** - * Test for <code>getInstance(String protocol, String provider)</code> - * method Assertion: throws IllegalArgumentException when provider is null - * or empty - */ - public void test_getInstanceLjava_lang_StringLjava_lang_String01() throws NoSuchProviderException, - NoSuchAlgorithmException { - if (!DEFSupported) { - fail(NotSupportMsg); - return; - } - String provider = null; - for (int i = 0; i < validValues.length; i++) { - try { - SSLContext.getInstance(defaultProtocol, provider); - fail("IllegalArgumentException must be thrown when provider is null"); - } catch (IllegalArgumentException e) { - } - try { - SSLContext.getInstance(defaultProtocol, ""); - fail("IllegalArgumentException must be thrown when provider is empty"); - } catch (IllegalArgumentException e) { - } - } - } - - /** - * Test for <code>getInstance(String protocol, String provider)</code> - * method Assertion: throws NullPointerException when protocol is null; - * throws NoSuchAlgorithmException when protocol is not correct; - */ - public void test_getInstanceLjava_lang_StringLjava_lang_String02() throws NoSuchProviderException { - if (!DEFSupported) { - fail(NotSupportMsg); - return; - } - try { - SSLContext.getInstance(null, defaultProviderName); - fail("NoSuchAlgorithmException or NullPointerException should be thrown (protocol is null"); - } catch (NoSuchAlgorithmException e) { - } catch (NullPointerException e) { - } - for (int i = 0; i < invalidValues.length; i++) { - try { - SSLContext.getInstance(invalidValues[i], defaultProviderName); - fail("NoSuchAlgorithmException was not thrown as expected (protocol: " - .concat(invalidValues[i]).concat(")")); - } catch (NoSuchAlgorithmException e) { - } - } - } - - /** - * Test for <code>getInstance(String protocol, String provider)</code> - * method Assertion: throws NoSuchProviderException when provider has - * invalid value - */ - public void test_getInstanceLjava_lang_StringLjava_lang_String03() throws NoSuchAlgorithmException { - if (!DEFSupported) { - fail(NotSupportMsg); - return; - } - for (int i = 1; i < invalidValues.length; i++) { - for (int j = 0; j < validValues.length; j++) { - try { - SSLContext.getInstance(validValues[j], invalidValues[i]); - fail("NuSuchProviderException must be thrown (protocol: " - .concat(validValues[j]).concat(" provider: ") - .concat(invalidValues[i]).concat(")")); - } catch (NoSuchProviderException e) { - } - } - } - } - - /** - * Test for <code>getInstance(String protocol, String provider)</code> - * method Assertion: returns instance of SSLContext - */ - public void test_getInstanceLjava_lang_StringLjava_lang_String04() throws NoSuchAlgorithmException, - NoSuchProviderException { - if (!DEFSupported) { - fail(NotSupportMsg); - return; - } - SSLContext sslContext; - for (int i = 0; i < validValues.length; i++) { - sslContext = SSLContext.getInstance(validValues[i], - defaultProviderName); - assertNotNull("Not SSLContext created", sslContext); - assertEquals("Invalid protocol", - validValues[i], sslContext.getProtocol()); - assertEquals("Invalid provider", - defaultProvider, sslContext.getProvider()); - } - } - - /** - * Test for <code>getInstance(String protocol, Provider provider)</code> - * method Assertion: throws IllegalArgumentException when provider is null - */ - public void test_getInstanceLjava_lang_StringLjava_security_Provider01() throws NoSuchAlgorithmException { - if (!DEFSupported) { - fail(NotSupportMsg); - return; - } - Provider provider = null; - for (int i = 0; i < validValues.length; i++) { - try { - SSLContext.getInstance(validValues[i], provider); - fail("IllegalArgumentException must be thrown when provider is null"); - } catch (IllegalArgumentException e) { - } - } - } - - /** - * Test for <code>getInstance(String protocol, Provider provider)</code> - * method Assertion: throws NullPointerException when protocol is null; - * throws NoSuchAlgorithmException when protocol is not correct; - */ - public void test_getInstanceLjava_lang_StringLjava_security_Provider02() { - if (!DEFSupported) { - fail(NotSupportMsg); - return; - } - try { - SSLContext.getInstance(null, defaultProvider); - fail("NoSuchAlgorithmException or NullPointerException should be thrown (protocol is null"); - } catch (NoSuchAlgorithmException e) { - } catch (NullPointerException e) { - } - for (int i = 0; i < invalidValues.length; i++) { - try { - SSLContext.getInstance(invalidValues[i], defaultProvider); - fail("Expected NoSuchAlgorithmException was not thrown as expected"); - } catch (NoSuchAlgorithmException e) { - } - } - } - - /** - * Test for <code>getInstance(String protocol, Provider provider)</code> - * method Assertion: returns instance of SSLContext - */ - public void test_getInstanceLjava_lang_StringLjava_security_Provider03() throws NoSuchAlgorithmException { - if (!DEFSupported) { - fail(NotSupportMsg); - return; - } - SSLContext sslContext; - for (int i = 0; i < validValues.length; i++) { - sslContext = SSLContext - .getInstance(validValues[i], defaultProvider); - assertNotNull("Not SSLContext created", sslContext); - assertEquals("Invalid protocol", validValues[i], sslContext.getProtocol()); - assertEquals("Invalid provider", defaultProvider, sslContext.getProvider()); - } - } - - /** - * @throws NoSuchAlgorithmException - * @throws NoSuchProviderException - * javax.net.ssl.SSLContext#getProtocol() - */ - public void test_getProtocol() - throws NoSuchAlgorithmException, NoSuchProviderException { - if (!DEFSupported) fail(NotSupportMsg); - SSLContextSpi spi = new MySSLContextSpi(); - SSLContext sslContext = new MySslContext(spi, defaultProvider, - defaultProtocol); - assertEquals("Incorrect protocol", - defaultProtocol, sslContext.getProtocol()); - sslContext = new MySslContext(spi, defaultProvider, - null); - assertNull("Incorrect protocol", sslContext.getProtocol()); - sslContext = SSLContext.getInstance(defaultProtocol); - assertEquals("Incorrect protocol", - defaultProtocol, sslContext.getProtocol()); - sslContext = SSLContext.getInstance(defaultProtocol, defaultProvider); - assertEquals("Incorrect protocol", - defaultProtocol, sslContext.getProtocol()); - sslContext = SSLContext.getInstance(defaultProtocol, defaultProviderName); - assertEquals("Incorrect protocol", - defaultProtocol, sslContext.getProtocol()); - } - - /** - * @throws NoSuchAlgorithmException - * @throws NoSuchProviderException - * javax.net.ssl.SSLContext#getProvider() - */ - public void test_getProvider() - throws NoSuchAlgorithmException, NoSuchProviderException { - if (!DEFSupported) fail(NotSupportMsg); - SSLContextSpi spi = new MySSLContextSpi(); - SSLContext sslContext = new MySslContext(spi, defaultProvider, - defaultProtocol); - assertEquals("Incorrect provider", - defaultProvider, sslContext.getProvider()); - sslContext = SSLContext.getInstance(defaultProtocol, defaultProvider); - assertEquals("Incorrect provider", - defaultProvider, sslContext.getProvider()); - sslContext = SSLContext.getInstance(defaultProtocol, defaultProviderName); - assertEquals("Incorrect provider", - defaultProvider, sslContext.getProvider()); - } - - /** - * javax.net.ssl.SSLContext#getServletSessionContext() - */ - public void test_getServerSessionContext() throws NoSuchAlgorithmException, - KeyManagementException, KeyStoreException, - UnrecoverableKeyException { - if (!DEFSupported) fail(NotSupportMsg); - SSLContext[] sslC = createSSLCon(); - assertNotNull("SSLContext objects were not created", sslC); - String tAlg = TrustManagerFactory.getDefaultAlgorithm(); - String kAlg = KeyManagerFactory.getDefaultAlgorithm(); - if (tAlg == null) - fail("TrustManagerFactory default algorithm is not defined"); - if (kAlg == null) - fail("KeyManagerFactory default algorithm is not defined"); - KeyManagerFactory kmf = KeyManagerFactory.getInstance(kAlg); - kmf.init(null, new char[11]); - TrustManagerFactory tmf = TrustManagerFactory.getInstance(tAlg); - KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); - tmf.init(ks); - TrustManager[] tms = tmf.getTrustManagers(); - for (SSLContext sslCi : sslC) { - sslCi.init(kmf.getKeyManagers(), tms, new SecureRandom()); - assertNotNull("Server context is incorrectly instantiated", sslCi - .getServerSessionContext()); - } - } - - /** - * Test for <code>getServerSocketFactory()</code> - * <code>getSocketFactory()</code> - * <code>init(KeyManager[] km, TrustManager[] tm, SecureRandom random)</code> - * methods Assertion: returns correspondent object - * - */ - public void test_getServerSocketFactory() throws NoSuchAlgorithmException, - KeyManagementException, KeyStoreException, - UnrecoverableKeyException { - if (!DEFSupported) { - fail(NotSupportMsg); - return; - } - SSLContext[] sslC = createSSLCon(); - assertNotNull("SSLContext objects were not created", sslC); - String tAlg = TrustManagerFactory.getDefaultAlgorithm(); - String kAlg = KeyManagerFactory.getDefaultAlgorithm(); - if (tAlg == null) { - fail("TrustManagerFactory default algorithm is not defined"); - return; - } - if (kAlg == null) { - fail("KeyManagerFactory default algorithm is not defined"); - return; - } - KeyManagerFactory kmf = KeyManagerFactory.getInstance(kAlg); - KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); - try { - ks.load(null, null); - } catch (Exception e) { - fail(e + " was thrown for method load(null, null)"); - } - kmf.init(ks, new char[10]); - KeyManager[] kms = kmf.getKeyManagers(); - TrustManagerFactory tmf = TrustManagerFactory.getInstance(tAlg); - tmf.init(ks); - TrustManager[] tms = tmf.getTrustManagers(); - for (int i = 0; i < sslC.length; i++) { - sslC[i].init(kms, tms, new SecureRandom()); - assertNotNull("No SSLServerSocketFactory available", - sslC[i].getServerSocketFactory()); - assertNotNull("No SSLSocketFactory available", - sslC[i].getSocketFactory()); - } - } - - /** - * javax.net.ssl.SSLContext#getSocketFactory() - */ - public void test_getSocketFactory() throws NoSuchAlgorithmException, - KeyManagementException, KeyStoreException, - UnrecoverableKeyException { - if (!DEFSupported) fail(NotSupportMsg); - SSLContext[] sslC = createSSLCon(); - assertNotNull("SSLContext objects were not created", sslC); - String tAlg = TrustManagerFactory.getDefaultAlgorithm(); - String kAlg = KeyManagerFactory.getDefaultAlgorithm(); - if (tAlg == null) - fail("TrustManagerFactory default algorithm is not defined"); - if (kAlg == null) - fail("KeyManagerFactory default algorithm is not defined"); - KeyManagerFactory kmf = KeyManagerFactory.getInstance(kAlg); - kmf.init(null, new char[11]); - TrustManagerFactory tmf = TrustManagerFactory.getInstance(tAlg); - KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); - tmf.init(ks); - TrustManager[] tms = tmf.getTrustManagers(); - for (SSLContext sslCi : sslC) { - sslCi.init(kmf.getKeyManagers(), tms, new SecureRandom()); - assertNotNull("Socket factory is incorrectly instantiated", - sslCi.getSocketFactory()); - } - } - - /** - * @throws NoSuchAlgorithmException - * @throws KeyStoreException - * @throws FileNotFoundException - * @throws KeyManagementException - * javax.net.ssl.SSLContext# - * init(javax.net.ssl.KeyManager[], javax.net.ssl.TrustManager[], - * java.security.SecureRandom) - */ - public void test_init$Ljavax_net_ssl_KeyManager$Ljavax_net_ssl_TrustManagerLjava_security_SecureRandom() - throws Exception { - if (!DEFSupported) fail(NotSupportMsg); - SSLContextSpi spi = new MySSLContextSpi(); - SSLContext sslContext = new MySslContext(spi, defaultProvider, - defaultProtocol); - try { - sslContext.createSSLEngine(); - fail("Expected RuntimeException was not thrown"); - } catch (RuntimeException rte) { - // expected - } - - try { - sslContext.init(null, null, null); - fail("KeyManagementException wasn't thrown"); - } catch (KeyManagementException kme) { - //expected - } - - try { - String tAlg = TrustManagerFactory.getDefaultAlgorithm(); - String kAlg = KeyManagerFactory.getDefaultAlgorithm(); - if (tAlg == null) - fail("TrustManagerFactory default algorithm is not defined"); - if (kAlg == null) - fail("KeyManagerFactory default algorithm is not defined"); - KeyManagerFactory kmf = KeyManagerFactory.getInstance(kAlg); - kmf.init(null, new char[11]); - TrustManagerFactory tmf = TrustManagerFactory.getInstance(tAlg); - KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); - tmf.init(ks); - TrustManager[] tms = tmf.getTrustManagers(); - sslContext.init(kmf.getKeyManagers(), tms, new SecureRandom()); - } catch (Exception e) { - System.out.println("EE = " + e); - } - } -} - -/** - * Addifional class to verify SSLContext constructor - */ - -class MySslContext extends SSLContext { - public MySslContext(SSLContextSpi spi, Provider prov, String alg) { - super(spi, prov, alg); - } -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLContext2Test.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLContext2Test.java deleted file mode 100644 index 0881615..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/SSLContext2Test.java +++ /dev/null @@ -1,293 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.net.ssl; - -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.SecureRandom; -import java.security.Security; -import javax.net.ssl.KeyManager; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLEngine; -import javax.net.ssl.TrustManager; -import junit.framework.TestCase; -import org.apache.harmony.security.tests.support.SpiEngUtils; -import org.apache.harmony.xnet.tests.support.MySSLContextSpi; - -/** - * Tests for SSLContext class constructors and methods - * - */ -public class SSLContext2Test extends TestCase { - - private static String srvSSLContext = "SSLContext"; - - private static final String defaultProtocol = "S+S+L"; - - public static final String SSLContextProviderClass = MySSLContextSpi.class.getName(); - - private static final String[] invalidValues = SpiEngUtils.invalidValues; - - private static final String[] validValues; - static { - validValues = new String[4]; - validValues[0] = defaultProtocol; - validValues[1] = defaultProtocol.toLowerCase(); - validValues[2] = "s+S+L"; - validValues[3] = "S+s+L"; - } - - Provider mProv; - - protected void setUp() throws Exception { - super.setUp(); - mProv = (new SpiEngUtils()).new MyProvider("MySSLContextProvider", "Provider for testing", - srvSSLContext.concat(".").concat(defaultProtocol), - SSLContextProviderClass); - Security.insertProviderAt(mProv, 1); - } - - /* - * @see TestCase#tearDown() - */ - protected void tearDown() throws Exception { - super.tearDown(); - Security.removeProvider(mProv.getName()); - } - - private void checkSSLContext(SSLContext sslC) - throws KeyManagementException { - - try { - sslC.getSocketFactory(); - fail("RuntimeException must be thrown"); - } catch (RuntimeException e) { - assertEquals("Incorrect message", "Not initialiazed", e.getMessage()); - } - try { - sslC.getServerSocketFactory(); - fail("RuntimeException must be thrown"); - } catch (RuntimeException e) { - assertEquals("Incorrect message", "Not initialiazed", e.getMessage()); - } - try { - sslC.getServerSessionContext(); - fail("RuntimeException must be thrown"); - } catch (RuntimeException e) { - assertEquals("Incorrect message", "Not initialiazed", e.getMessage()); - } - try { - sslC.getClientSessionContext(); - fail("RuntimeException must be thrown"); - } catch (RuntimeException e) { - assertEquals("Incorrect message", "Not initialiazed", e.getMessage()); - } - try { - sslC.createSSLEngine(); - fail("RuntimeException must be thrown"); - } catch (RuntimeException e) { - assertEquals("Incorrect message", "Not initialiazed", e.getMessage()); - } - try { - sslC.createSSLEngine("host",1); - fail("RuntimeException must be thrown"); - } catch (RuntimeException e) { - assertEquals("Incorrect message", "Not initialiazed", e.getMessage()); - } - TrustManager [] tm = new TManager[10]; - KeyManager [] km = new KManager[5]; - try { - sslC.init(km, tm, null); - fail("KeyManagementException must be thrown"); - } catch (KeyManagementException e) { - } - sslC.init(km, tm, new SecureRandom()); - - SSLEngine sslE = sslC.createSSLEngine(); - assertTrue("Not null result",sslE instanceof SSLEngine); - assertNull("Incorrect host", sslE.getPeerHost()); - assertEquals("Incorrect port", 0, sslE.getPeerPort()); - String host = "ZZZ"; - int port = 8080; - sslE = sslC.createSSLEngine(host, port); - assertTrue("Not null result",sslE instanceof SSLEngine); - assertEquals("Incorrect host", sslE.getPeerHost(), host); - assertEquals("Incorrect port", sslE.getPeerPort(), port); - try { - assertNull("Not null result", sslC.getServerSessionContext()); - } catch (NullPointerException e) { - } - try { - assertNull("Not null result", sslC.getClientSessionContext()); - } catch (NullPointerException e) { - } - } - - /** - * Test for <code>getInstance(String protocol)</code> method - * Assertions: - * throws NullPointerException when protocol is null; - * throws NoSuchAlgorithmException when protocol is not correct; - * returns SSLContext object - */ - public void test_getInstanceLjava_lang_String() throws NoSuchAlgorithmException, - KeyManagementException { - try { - SSLContext.getInstance(null); - fail("NoSuchAlgorithmException or NullPointerException should be thrown " - + "(protocol is null)"); - } catch (NoSuchAlgorithmException e) { - } catch (NullPointerException e) { - } - for (int i = 0; i < invalidValues.length; i++) { - try { - SSLContext.getInstance(invalidValues[i]); - fail("NoSuchAlgorithmException must be thrown (protocol: " - .concat(invalidValues[i]).concat(")")); - } catch (NoSuchAlgorithmException e) { - } - } - SSLContext sslC; - for (int i = 0; i < validValues.length; i++) { - sslC = SSLContext.getInstance(validValues[i]); - assertTrue("Not instanceof SSLContext object", sslC instanceof SSLContext); - assertEquals("Incorrect protocol", sslC.getProtocol(), validValues[i]); - assertEquals("Incorrect provider", sslC.getProvider(), mProv); - checkSSLContext(sslC); - } - } - - /** - * Test for <code>getInstance(String protocol, String provider)</code> - * method - * Assertions: - * throws NullPointerException when protocol is null; - * throws NoSuchAlgorithmException when protocol is not correct; - * throws IllegalArgumentException when provider is null or empty; - * throws NoSuchProviderException when provider is available; - * returns SSLContext object - */ - public void test_getInstanceLjava_lang_StringLjava_lang_String() - throws NoSuchAlgorithmException, NoSuchProviderException, - IllegalArgumentException, KeyManagementException { - try { - SSLContext.getInstance(null, mProv.getName()); - fail("NoSuchAlgorithmException or NullPointerException should be thrown " - + "(protocol is null)"); - } catch (NoSuchAlgorithmException e) { - } catch (NullPointerException e) { - } - for (int i = 0; i < invalidValues.length; i++) { - try { - SSLContext.getInstance(invalidValues[i], mProv.getName()); - fail("NoSuchAlgorithmException must be thrown (protocol: " - .concat(invalidValues[i]).concat(")")); - } catch (NoSuchAlgorithmException e) { - } - } - String prov = null; - for (int i = 0; i < validValues.length; i++) { - try { - SSLContext.getInstance(validValues[i], prov); - fail("IllegalArgumentException must be thrown when provider is null (protocol: " - .concat(invalidValues[i]).concat(")")); - } catch (IllegalArgumentException e) { - } - try { - SSLContext.getInstance(validValues[i], ""); - fail("IllegalArgumentException must be thrown when provider is empty (protocol: " - .concat(invalidValues[i]).concat(")")); - } catch (IllegalArgumentException e) { - } - } - for (int i = 0; i < validValues.length; i++) { - for (int j = 1; j < invalidValues.length; j++) { - try { - SSLContext.getInstance(validValues[i], invalidValues[j]); - fail("NoSuchProviderException must be thrown (protocol: " - .concat(invalidValues[i]).concat(" provider: ") - .concat(invalidValues[j]).concat(")")); - } catch (NoSuchProviderException e) { - } - } - } - SSLContext sslC; - for (int i = 0; i < validValues.length; i++) { - sslC = SSLContext.getInstance(validValues[i], mProv.getName()); - assertTrue("Not instanceof SSLContext object", sslC instanceof SSLContext); - assertEquals("Incorrect protocol", sslC.getProtocol(), validValues[i]); - assertEquals("Incorrect provider", sslC.getProvider().getName(), mProv.getName()); - checkSSLContext(sslC); - } - } - - /** - * Test for <code>getInstance(String protocol, Provider provider)</code> - * method - * Assertions: - * throws NullPointerException when protocol is null; - * throws NoSuchAlgorithmException when protocol is not correct; - * throws IllegalArgumentException when provider is null; - * returns SSLContext object - */ - public void test_getInstanceLjava_lang_StringLjava_security_Provider() - throws NoSuchAlgorithmException, - IllegalArgumentException, KeyManagementException { - try { - SSLContext.getInstance(null, mProv); - fail("NoSuchAlgorithmException or NullPointerException should be thrown " - + "(protocol is null)"); - } catch (NoSuchAlgorithmException e) { - } catch (NullPointerException e) { - } - for (int i = 0; i < invalidValues.length; i++) { - try { - SSLContext.getInstance(invalidValues[i], mProv); - fail("NoSuchAlgorithmException must be thrown (protocol: " - .concat(invalidValues[i]).concat(")")); - } catch (NoSuchAlgorithmException e) { - } - } - Provider prov = null; - for (int i = 0; i < validValues.length; i++) { - try { - SSLContext.getInstance(validValues[i], prov); - fail("IllegalArgumentException must be thrown when provider is null (protocol: " - .concat(invalidValues[i]).concat(")")); - } catch (IllegalArgumentException e) { - } - } - SSLContext sslC; - for (int i = 0; i < validValues.length; i++) { - sslC = SSLContext.getInstance(validValues[i], mProv); - assertTrue("Not instanceof SSLContext object", sslC instanceof SSLContext); - assertEquals("Incorrect protocol", sslC.getProtocol(), validValues[i]); - assertEquals("Incorrect provider", sslC.getProvider(), mProv); - checkSSLContext(sslC); - } - } - - class TManager implements TrustManager { - - } - class KManager implements KeyManager { - - } -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLContextSpiTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLContextSpiTest.java deleted file mode 100644 index 45a1c14..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/SSLContextSpiTest.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.javax.net.ssl; - -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContextSpi; -import javax.net.ssl.SSLEngine; -import javax.net.ssl.SSLServerSocketFactory; -import javax.net.ssl.SSLSessionContext; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.KeyManager; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import java.security.KeyManagementException; - -import java.security.KeyStore; -import java.security.SecureRandom; -import java.security.Security; - -import junit.framework.TestCase; - -import org.apache.harmony.xnet.tests.support.SSLContextSpiImpl; - -public class SSLContextSpiTest extends TestCase { - - /** - * javax.net.ssl.SSLContextSpi#SSLContextSpi() - */ - public void test_Constructor() { - try { - SSLContextSpiImpl ssl = new SSLContextSpiImpl(); - assertTrue(ssl instanceof SSLContextSpi); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - /** - * javax.net.ssl.SSLContextSpi#engineCreateSSLEngine() - * Verify exception when SSLContextSpi object wasn't initialiazed. - */ - public void test_engineCreateSSLEngine_01() { - SSLContextSpiImpl ssl = new SSLContextSpiImpl(); - try { - SSLEngine sleng = ssl.engineCreateSSLEngine(); - fail("RuntimeException wasn't thrown"); - } catch (RuntimeException re) { - String str = re.getMessage(); - if (!str.equals("Not initialiazed")) - fail("Incorrect exception message: " + str); - } catch (Exception e) { - fail("Incorrect exception " + e + " was thrown"); - } - } - - /** - * javax.net.ssl.SSLContextSpi#engineCreateSSLEngine(String host, int port) - * Verify exception when SSLContextSpi object wasn't initialiazed. - */ - public void test_engineCreateSSLEngine_02() { - int[] invalid_port = {Integer.MIN_VALUE, -65535, -1, 65536, Integer.MAX_VALUE}; - SSLContextSpiImpl ssl = new SSLContextSpiImpl(); - try { - SSLEngine sleng = ssl.engineCreateSSLEngine("localhost", 1080); - fail("RuntimeException wasn't thrown"); - } catch (RuntimeException re) { - String str = re.getMessage(); - if (!str.equals("Not initialiazed")) - fail("Incorrect exception message: " + str); - } catch (Exception e) { - fail("Incorrect exception " + e + " was thrown"); - } - - for (int i = 0; i < invalid_port.length; i++) { - try { - SSLEngine sleng = ssl.engineCreateSSLEngine("localhost", invalid_port[i]); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iae) { - //expected - } - } - } - - /** - * SSLContextSpi#engineGetClientSessionContext() - * SSLContextSpi#engineGetServerSessionContext() - * SSLContextSpi#engineGetServerSocketFactory() - * SSLContextSpi#engineGetSocketFactory() - * Verify exception when SSLContextSpi object wasn't initialiazed. - */ - public void test_commonTest_01() { - SSLContextSpiImpl ssl = new SSLContextSpiImpl(); - - try { - SSLSessionContext slsc = ssl.engineGetClientSessionContext(); - fail("RuntimeException wasn't thrown"); - } catch (RuntimeException re) { - String str = re.getMessage(); - if (!str.equals("Not initialiazed")) - fail("Incorrect exception message: " + str); - } catch (Exception e) { - fail("Incorrect exception " + e + " was thrown"); - } - - try { - SSLSessionContext slsc = ssl.engineGetServerSessionContext(); - fail("RuntimeException wasn't thrown"); - } catch (RuntimeException re) { - String str = re.getMessage(); - if (!str.equals("Not initialiazed")) - fail("Incorrect exception message: " + str); - } catch (Exception e) { - fail("Incorrect exception " + e + " was thrown"); - } - - try { - SSLServerSocketFactory sssf = ssl.engineGetServerSocketFactory(); - fail("RuntimeException wasn't thrown"); - } catch (RuntimeException re) { - String str = re.getMessage(); - if (!str.equals("Not initialiazed")) - fail("Incorrect exception message: " + str); - } catch (Exception e) { - fail("Incorrect exception " + e + " was thrown"); - } - - try { - SSLSocketFactory ssf = ssl.engineGetSocketFactory(); - fail("RuntimeException wasn't thrown"); - } catch (RuntimeException re) { - String str = re.getMessage(); - if (!str.equals("Not initialiazed")) - fail("Incorrect exception message: " + str); - } catch (Exception e) { - fail("Incorrect exception " + e + " was thrown"); - } - } - - /** - * SSLContextSpi#engineInit(KeyManager[] km, TrustManager[] tm, SecureRandom sr) - */ - public void test_engineInit() { - SSLContextSpiImpl ssl = new SSLContextSpiImpl(); - String defaultAlgorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm"); - try { - KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm); - char[] pass = "password".toCharArray(); - kmf.init(null, pass); - KeyManager[] km = kmf.getKeyManagers(); - defaultAlgorithm = Security.getProperty("ssl.TrustManagerFactory.algorithm"); - TrustManagerFactory trustMF = TrustManagerFactory.getInstance(defaultAlgorithm); - KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); - ks.load(null, null); - trustMF.init(ks); - TrustManager[] tm = trustMF.getTrustManagers(); - SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); - try { - ssl.engineInit(km, tm, sr); - } catch (KeyManagementException kme) { - fail(kme + " was throw for engineInit method"); - } - try { - ssl.engineInit(km, tm, null); - fail("KeyManagementException wasn't thrown"); - } catch (KeyManagementException kme) { - //expected - } - } catch (Exception ex) { - fail(ex + " unexpected exception"); - } - } - - /** - * SSLContextSpi#engineCreateSSLEngine() - * SSLContextSpi#engineCreateSSLEngine(String host, int port) - * SSLContextSpi#engineGetClientSessionContext() - * SSLContextSpi#engineGetServerSessionContext() - * SSLContextSpi#engineGetServerSocketFactory() - * SSLContextSpi#engineGetSocketFactory() - */ - public void test_commonTest_02() { - SSLContextSpiImpl ssl = new SSLContextSpiImpl(); - String defaultAlgorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm"); - try { - KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm); - char[] pass = "password".toCharArray(); - kmf.init(null, pass); - KeyManager[] km = kmf.getKeyManagers(); - defaultAlgorithm = Security.getProperty("ssl.TrustManagerFactory.algorithm"); - TrustManagerFactory trustMF = TrustManagerFactory.getInstance(defaultAlgorithm); - KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); - ks.load(null, null); - trustMF.init(ks); - TrustManager[] tm = trustMF.getTrustManagers(); - SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); - ssl.engineInit(km, tm, sr); - } catch (Exception ex) { - fail(ex + " unexpected exception"); - } - - try { - assertNotNull("Subtest_01: Object is NULL", ssl.engineCreateSSLEngine()); - SSLEngine sleng = ssl.engineCreateSSLEngine("localhost", 1080); - assertNotNull("Subtest_02: Object is NULL", sleng); - assertEquals(sleng.getPeerPort(), 1080); - assertEquals(sleng.getPeerHost(), "localhost"); - assertNull("Subtest_03: Object not NULL", ssl.engineGetClientSessionContext()); - assertNull("Subtest_04: Object not NULL", ssl.engineGetServerSessionContext()); - assertNull("Subtest_05: Object not NULL", ssl.engineGetServerSocketFactory()); - assertNull("Subtest_06: Object not NULL", ssl.engineGetSocketFactory()); - } catch (Exception e) { - fail("Unexpected exception " + e); - } - } - -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineResultHandshakeStatusTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineResultHandshakeStatusTest.java deleted file mode 100644 index 3b13673..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineResultHandshakeStatusTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.net.ssl; - -import javax.net.ssl.SSLEngineResult; - -import junit.framework.TestCase; - -/** - * Tests for SSLEngineResult.Status class - * - */ -public class SSLEngineResultHandshakeStatusTest extends TestCase { - - /** - * Test for <code> SSLEngineResult.HandshakeStatus.values() </code> - */ - public void test_SSLEngineResultHandshakeStatus_values() { - String[] str = {"NOT_HANDSHAKING", "FINISHED", "NEED_TASK", "NEED_WRAP", "NEED_UNWRAP"}; - SSLEngineResult.HandshakeStatus[] enS = SSLEngineResult.HandshakeStatus.values(); - if (enS.length == str.length) { - for (int i = 0; i < enS.length; i++) { - //System.out.println("enS[" + i + "] = " + enS[i]); - assertEquals("Incorrect Status", enS[i].toString(), str[i]); - } - } else { - fail("Incorrect number of enum constant was returned"); - } - } - - /** - * Test for <code> SSLEngineResult.HandshakeStatus.valueOf(String name) </code> - */ - public void test_SSLEngineResultStatus_valueOf() { - String[] str = {"FINISHED", "NEED_TASK", "NEED_UNWRAP", "NEED_WRAP", "NOT_HANDSHAKING"}; - String[] str_invalid = {"", "FINISHED1", "NEED_task", "NEED_UN", - "NEED_WRAP_WRAP", "not_HANDSHAKING", "Bad string for verification valueOf method"}; - SSLEngineResult.HandshakeStatus enS; - - //Correct parameter - for (int i = 0; i < str.length; i++) { - try { - enS = SSLEngineResult.HandshakeStatus.valueOf(str[i]); - assertEquals("Incorrect Status", enS.toString(), str[i]); - } catch (Exception e) { - fail("Unexpected exception " + e + " was thrown for " + str[i]); - } - } - - //Incorrect parameter - for (int i = 0; i < str_invalid.length; i++) { - try { - enS = SSLEngineResult.HandshakeStatus.valueOf(str_invalid[i]); - fail("IllegalArgumentException should be thrown for " + str_invalid[i]); - } catch (IllegalArgumentException iae) { - //expected - } - } - - //Null parameter - try { - enS = SSLEngineResult.HandshakeStatus.valueOf(null); - fail("NullPointerException/IllegalArgumentException should be thrown for NULL parameter"); - } catch (NullPointerException npe) { - //expected - } catch (IllegalArgumentException iae) { - } - } -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineResultStatusTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineResultStatusTest.java deleted file mode 100644 index 05c8f03..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineResultStatusTest.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.net.ssl; - -import javax.net.ssl.SSLEngineResult; - -import junit.framework.TestCase; - -/** - * Tests for SSLEngineResult.Status class - * - */ -public class SSLEngineResultStatusTest extends TestCase { - - /** - * Test for <code> SSLEngineResult.Status.values() </code> - */ - public void test_SSLEngineResultStatus_values() { - boolean flag = false; - String[] str = {"BUFFER_OVERFLOW", "BUFFER_UNDERFLOW", "CLOSED", "OK"}; - SSLEngineResult.Status[] enS = SSLEngineResult.Status.values(); - if (enS.length == str.length) { - for (int i = 0; i < enS.length; i++) { - flag = false; - for (int j = 0; j < str.length; j++) { - if (enS[i].toString() == str[j]) { - flag = true; - break; - } - } - } - assertTrue("Incorrect Status", flag); - } else { - fail("Incorrect number of enum constant was returned"); - } - } - - /** - * Test for <code> SSLEngineResult.Status.valueOf(String name) </code> - */ - public void test_SSLEngineResultStatus_valueOf() { - String[] str = {"BUFFER_OVERFLOW", "BUFFER_UNDERFLOW", "CLOSED", "OK"}; - String[] str_invalid = {"", "OK1", "BUFFER_overflow", "BUFFER_UND", - "CLOSED_CLOSED", "Bad string for verification valueOf method"}; - SSLEngineResult.Status enS; - - //Correct parameter - for (int i = 0; i < str.length; i++) { - try { - enS = SSLEngineResult.Status.valueOf(str[i]); - assertEquals("Incorrect Status", enS.toString(), str[i]); - } catch (Exception e) { - fail("Unexpected exception " + e + " was thrown for " + str[i]); - } - } - - //Incorrect parameter - for (int i = 0; i < str_invalid.length; i++) { - try { - enS = SSLEngineResult.Status.valueOf(str_invalid[i]); - fail("IllegalArgumentException should be thrown for " + str_invalid[i]); - } catch (IllegalArgumentException iae) { - //expected - } - } - - //Null parameter - try { - enS = SSLEngineResult.Status.valueOf(null); - fail("NullPointerException/IllegalArgumentException should be thrown for NULL parameter"); - } catch (NullPointerException npe) { - //expected - } catch (IllegalArgumentException iae) { - } - } -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineResultTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineResultTest.java deleted file mode 100644 index 7a2ac78..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineResultTest.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.net.ssl; - -import javax.net.ssl.SSLEngineResult; -import junit.framework.TestCase; - - -/** - * Tests for SSLEngineResult class - * - */ -public class SSLEngineResultTest extends TestCase { - - /** - * Test for <code>SSLEngineResult(SSLEngineResult.Status status, - * SSLEngineResult.HandshakeStatus handshakeStatus, - * int bytesConsumed, - * int bytesProduced) </code> constructor and - * <code>getHandshakeStatus()</code> - * <code>getStatus()</code> - * <code>bytesConsumed()</code> - * <code>bytesProduced()</code> - * <code>toString()</code> - * methods - * Assertions: - * constructor throws IllegalArgumentException when bytesConsumed - * or bytesProduced is negative or when status or handshakeStatus - * is null - * - */ - public void test_ConstructorLjavax_net_ssl_SSLEngineResult_StatusLjavax_net_ssl_SSLEngineResult_HandshakeStatusII() { - - int[] neg = { -1, -10, -1000, Integer.MIN_VALUE, - (Integer.MIN_VALUE + 1) }; - try { - new SSLEngineResult(null, SSLEngineResult.HandshakeStatus.FINISHED, - 1, 1); - fail("IllegalArgumentException must be thrown"); - } catch (IllegalArgumentException e) { - } - try { - new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW, null, - 1, 1); - fail("IllegalArgumentException must be thrown"); - } catch (IllegalArgumentException e) { - } - for (int i = 0; i < neg.length; i++) { - try { - new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW, - SSLEngineResult.HandshakeStatus.FINISHED, neg[i], 1); - fail("IllegalArgumentException must be thrown"); - } catch (IllegalArgumentException e) { - } - } - for (int i = 0; i < neg.length; i++) { - try { - new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW, - SSLEngineResult.HandshakeStatus.FINISHED, 1, neg[i]); - fail("IllegalArgumentException must be thrown"); - } catch (IllegalArgumentException e) { - } - } - - try { - SSLEngineResult res = new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW, - SSLEngineResult.HandshakeStatus.FINISHED, 1, 2); - assertNotNull("Null object", res); - assertEquals(1, res.bytesConsumed()); - assertEquals(2, res.bytesProduced()); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - } - - /** - * Test for <code>bytesConsumed()</code> method - */ - public void test_bytesConsumed() { - int[] pos = { 0, 1, 1000, Integer.MAX_VALUE, (Integer.MAX_VALUE - 1) }; - SSLEngineResult.Status [] enS = - SSLEngineResult.Status.values(); - SSLEngineResult.HandshakeStatus [] enHS = - SSLEngineResult.HandshakeStatus.values(); - for (int i = 0; i < enS.length; i++) { - for (int j = 0; j < enHS.length; j++) { - for (int n = 0; n < pos.length; n++) { - for (int l = 0; l < pos.length; l++) { - SSLEngineResult res = new SSLEngineResult(enS[i], - enHS[j], pos[n], pos[l]); - assertEquals("Incorrect bytesConsumed", pos[n], - res.bytesConsumed()); - } - } - } - } - } - - /** - * Test for <code>bytesProduced()</code> method - */ - public void test_bytesProduced() { - int[] pos = { 0, 1, 1000, Integer.MAX_VALUE, (Integer.MAX_VALUE - 1) }; - SSLEngineResult.Status [] enS = - SSLEngineResult.Status.values(); - SSLEngineResult.HandshakeStatus [] enHS = - SSLEngineResult.HandshakeStatus.values(); - for (int i = 0; i < enS.length; i++) { - for (int j = 0; j < enHS.length; j++) { - for (int n = 0; n < pos.length; n++) { - for (int l = 0; l < pos.length; ++l) { - SSLEngineResult res = new SSLEngineResult(enS[i], - enHS[j], pos[n], pos[l]); - assertEquals("Incorrect bytesProduced", pos[l], - res.bytesProduced()); - } - } - } - } - } - - /** - * Test for <code>getHandshakeStatus()</code> method - */ - public void test_getHandshakeStatus() { - int[] pos = { 0, 1, 1000, Integer.MAX_VALUE, (Integer.MAX_VALUE - 1) }; - SSLEngineResult.Status [] enS = - SSLEngineResult.Status.values(); - SSLEngineResult.HandshakeStatus [] enHS = - SSLEngineResult.HandshakeStatus.values(); - for (int i = 0; i < enS.length; i++) { - for (int j = 0; j < enHS.length; j++) { - for (int n = 0; n < pos.length; n++) { - for (int l = 0; l < pos.length; ++l) { - SSLEngineResult res = new SSLEngineResult(enS[i], - enHS[j], pos[n], pos[l]); - assertEquals("Incorrect HandshakeStatus", enHS[j], - res.getHandshakeStatus()); - } - } - } - } - } - - /** - * Test for <code>getStatus()</code> method - */ - public void test_getStatus() { - int[] pos = { 0, 1, 1000, Integer.MAX_VALUE, (Integer.MAX_VALUE - 1) }; - SSLEngineResult.Status [] enS = - SSLEngineResult.Status.values(); - SSLEngineResult.HandshakeStatus [] enHS = - SSLEngineResult.HandshakeStatus.values(); - for (int i = 0; i < enS.length; i++) { - for (int j = 0; j < enHS.length; j++) { - for (int n = 0; n < pos.length; n++) { - for (int l = 0; l < pos.length; ++l) { - SSLEngineResult res = new SSLEngineResult(enS[i], - enHS[j], pos[n], pos[l]); - assertEquals("Incorrect Status", enS[i], - res.getStatus()); - } - } - } - } - } - - /** - * Test for <code>toString()</code> method - */ - public void test_toString() { - int[] pos = { 0, 1, 1000, Integer.MAX_VALUE, (Integer.MAX_VALUE - 1) }; - SSLEngineResult.Status [] enS = - SSLEngineResult.Status.values(); - SSLEngineResult.HandshakeStatus [] enHS = - SSLEngineResult.HandshakeStatus.values(); - for (int i = 0; i < enS.length; i++) { - for (int j = 0; j < enHS.length; j++) { - for (int n = 0; n < pos.length; n++) { - for (int l = 0; l < pos.length; ++l) { - SSLEngineResult res = new SSLEngineResult(enS[i], - enHS[j], pos[n], pos[l]); - assertNotNull("Result of toSring() method is null", - res.toString()); - } - } - } - } - } - - private boolean findEl(Object[] arr, Object el) { - boolean ok = false; - for (int i = 0; i < arr.length; i++) { - if (arr[i].equals(el)) { - ok = true; - break; - } - } - return ok; - } - -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java deleted file mode 100644 index 30a1a9c..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java +++ /dev/null @@ -1,1482 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.net.ssl; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.ReadOnlyBufferException; -import java.nio.channels.Pipe; -import java.nio.channels.Pipe.SinkChannel; -import java.nio.channels.Pipe.SourceChannel; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLEngine; -import javax.net.ssl.SSLEngineResult; -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLEngineResult.HandshakeStatus; - -import junit.framework.TestCase; -import dalvik.annotation.AndroidOnly; -import dalvik.annotation.KnownFailure; - - -/** - * Tests for SSLEngine class - * - */ -public class SSLEngineTest extends TestCase { - - private HandshakeHandler clientEngine; - private HandshakeHandler serverEngine; - - @Override protected void setUp() throws Exception { - super.setUp(); - } - - /** - * Test for <code>SSLEngine()</code> constructor Assertion: creates - * SSLEngine object with null host and -1 port - * @throws NoSuchAlgorithmException - */ - public void test_Constructor() throws NoSuchAlgorithmException { - SSLEngine e = getEngine(); - assertNull(e.getPeerHost()); - assertEquals(-1, e.getPeerPort()); - String[] suites = e.getSupportedCipherSuites(); - e.setEnabledCipherSuites(suites); - assertEquals(e.getEnabledCipherSuites().length, suites.length); - } - - /** - * Test for <code>SSLEngine(String host, int port)</code> constructor - * @throws NoSuchAlgorithmException - */ - public void test_ConstructorLjava_lang_StringI01() throws NoSuchAlgorithmException { - int port = 1010; - SSLEngine e = getEngine(null, port); - assertNull(e.getPeerHost()); - assertEquals(e.getPeerPort(), port); - try { - e.beginHandshake(); - } catch (IllegalStateException ex) { - // expected - } catch (SSLException ex) { - fail("unexpected SSLException was thrown."); - } - e = getEngine(null, port); - e.setUseClientMode(true); - try { - e.beginHandshake(); - } catch (SSLException ex) { - // expected - } - e = getEngine(null, port); - e.setUseClientMode(false); - try { - e.beginHandshake(); - } catch (SSLException ex) { - // expected - } - } - - /** - * Test for <code>SSLEngine(String host, int port)</code> constructor - * @throws NoSuchAlgorithmException - */ - public void test_ConstructorLjava_lang_StringI02() throws NoSuchAlgorithmException { - String host = "new host"; - int port = 8080; - SSLEngine e = getEngine(host, port); - assertEquals(e.getPeerHost(), host); - assertEquals(e.getPeerPort(), port); - String[] suites = e.getSupportedCipherSuites(); - e.setEnabledCipherSuites(suites); - assertEquals(e.getEnabledCipherSuites().length, suites.length); - e.setUseClientMode(true); - assertTrue(e.getUseClientMode()); - } - - /** - * Test for <code>getPeerHost()</code> method - * @throws NoSuchAlgorithmException - */ - public void test_getPeerHost() throws NoSuchAlgorithmException { - SSLEngine e = getEngine(); - assertNull(e.getPeerHost()); - e = getEngine("www.fortify.net", 80); - assertEquals("Incorrect host name", "www.fortify.net", e.getPeerHost()); - } - - /** - * Test for <code>getPeerPort()</code> method - * @throws NoSuchAlgorithmException - */ - public void test_getPeerPort() throws NoSuchAlgorithmException { - SSLEngine e = getEngine(); - assertEquals("Incorrect default value of peer port", - -1 ,e.getPeerPort()); - e = getEngine("www.fortify.net", 80); - assertEquals("Incorrect peer port", 80, e.getPeerPort()); - } - - /** - * @throws NoSuchAlgorithmException - * javax.net.ssl.SSLEngine#getSupportedProtocols() - */ - public void test_getSupportedProtocols() throws NoSuchAlgorithmException { - SSLEngine sse = getEngine(); - try { - String[] res = sse.getSupportedProtocols(); - assertNotNull(res); - assertTrue(res.length > 0); - } catch (Exception ex) { - fail("Unexpected exception " + ex); - } - } - - /** - * @throws NoSuchAlgorithmException - * javax.net.ssl.SSLEngine#setEnabledProtocols(String[] protocols) - * javax.net.ssl.SSLEngine#getEnabledProtocols() - */ - public void test_EnabledProtocols() throws NoSuchAlgorithmException { - SSLEngine sse = getEngine(); - String[] pr = sse.getSupportedProtocols(); - try { - sse.setEnabledProtocols(pr); - String[] res = sse.getEnabledProtocols(); - assertNotNull("Null array was returned", res); - assertEquals("Incorrect array length", res.length, pr.length); - assertTrue("Incorrect array was returned", Arrays.equals(res, pr)); - } catch (Exception ex) { - fail("Unexpected exception " + ex); - } - try { - sse.setEnabledProtocols(null); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iae) { - //expected - } - } - - /** - * @throws NoSuchAlgorithmException - * javax.net.ssl.SSLEngine#getSupportedCipherSuites() - */ - public void test_getSupportedCipherSuites() throws NoSuchAlgorithmException { - SSLEngine sse = getEngine(); - try { - String[] res = sse.getSupportedCipherSuites(); - assertNotNull(res); - assertTrue(res.length > 0); - } catch (Exception ex) { - fail("Unexpected exception " + ex); - } - } - - /** - * @throws NoSuchAlgorithmException - * javax.net.ssl.SSLEngine#setEnabledCipherSuites(String[] suites) - * javax.net.ssl.SSLEngine#getEnabledCipherSuites() - */ - public void test_EnabledCipherSuites() throws NoSuchAlgorithmException { - SSLEngine sse = getEngine(); - String[] st = sse.getSupportedCipherSuites(); - try { - sse.setEnabledCipherSuites(st); - String[] res = sse.getEnabledCipherSuites(); - assertNotNull("Null array was returned", res); - assertEquals("Incorrect array length", res.length, st.length); - assertTrue("Incorrect array was returned", Arrays.equals(res, st)); - } catch (Exception ex) { - fail("Unexpected exception " + ex); - } - try { - sse.setEnabledCipherSuites(null); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iae) { - //expected - } - } - - /** - * @throws NoSuchAlgorithmException - * javax.net.ssl.SSLEngine#setEnableSessionCreation(boolean flag) - * javax.net.ssl.SSLEngine#getEnableSessionCreation() - */ - public void test_EnableSessionCreation() throws NoSuchAlgorithmException { - SSLEngine sse = getEngine(); - try { - assertTrue(sse.getEnableSessionCreation()); - sse.setEnableSessionCreation(false); - assertFalse(sse.getEnableSessionCreation()); - sse.setEnableSessionCreation(true); - assertTrue(sse.getEnableSessionCreation()); - } catch (Exception ex) { - fail("Unexpected exception " + ex); - } - } - - /** - * @throws NoSuchAlgorithmException - * javax.net.ssl.SSLEngine#setNeedClientAuth(boolean need) - * javax.net.ssl.SSLEngine#getNeedClientAuth() - */ - public void test_NeedClientAuth() throws NoSuchAlgorithmException { - SSLEngine sse = getEngine(); - try { - sse.setNeedClientAuth(false); - assertFalse(sse.getNeedClientAuth()); - sse.setNeedClientAuth(true); - assertTrue(sse.getNeedClientAuth()); - } catch (Exception ex) { - fail("Unexpected exception " + ex); - } - } - - /** - * @throws NoSuchAlgorithmException - * javax.net.ssl.SSLEngine#setWantClientAuth(boolean want) - * javax.net.ssl.SSLEngine#getWantClientAuth() - */ - public void test_WantClientAuth() throws NoSuchAlgorithmException { - SSLEngine sse = getEngine(); - try { - sse.setWantClientAuth(false); - assertFalse(sse.getWantClientAuth()); - sse.setWantClientAuth(true); - assertTrue(sse.getWantClientAuth()); - } catch (Exception ex) { - fail("Unexpected exception " + ex); - } - } - - /** - * @throws NoSuchAlgorithmException - * javax.net.ssl.SSLEngine#beginHandshake() - */ - public void test_beginHandshake() throws NoSuchAlgorithmException { - SSLEngine sse = getEngine(); - try { - sse.beginHandshake(); - fail("IllegalStateException wasn't thrown"); - } catch (IllegalStateException se) { - //expected - } catch (Exception e) { - fail(e + " was thrown instead of IllegalStateException"); - } - sse = getEngine("new host", 1080); - try { - sse.beginHandshake(); - fail("IllegalStateException wasn't thrown"); - } catch (IllegalStateException ise) { - //expected - } catch (Exception e) { - fail(e + " was thrown instead of IllegalStateException"); - } - sse = getEngine(); - try { - sse.setUseClientMode(true); - sse.beginHandshake(); - } catch (Exception ex) { - fail("Unexpected exception " + ex); - } - } - - /** - * @throws NoSuchAlgorithmException - * javax.net.ssl.SSLEngine#setUseClientMode(boolean mode) - * javax.net.ssl.SSLEngine#getUseClientMode() - */ - @AndroidOnly("The RI doesn't throw the expected IllegalStateException.") - public void test_UseClientMode() throws NoSuchAlgorithmException { - SSLEngine sse = getEngine(); - try { - sse.setUseClientMode(false); - assertFalse(sse.getUseClientMode()); - sse.setUseClientMode(true); - assertTrue(sse.getUseClientMode()); - } catch (Exception ex) { - fail("Unexpected exception " + ex); - } - - try { - sse = getEngine(null, 1080); - sse.setUseClientMode(true); - sse.beginHandshake(); - try { - sse.setUseClientMode(false); - fail("IllegalArgumentException was not thrown"); - } catch (IllegalArgumentException iae) { - //expected - } - } catch (Exception ex) { - fail("Unexpected exception " + ex); - } - } - - /** - * @throws NoSuchAlgorithmException - * javax.net.ssl.SSLEngine#getSession() - */ - public void test_getSession() throws NoSuchAlgorithmException { - SSLEngine sse = getEngine(); - try { - assertNotNull(sse.getSession()); - } catch (Exception ex) { - fail("Unexpected exception " + ex); - } - } - - /** - * @throws NoSuchAlgorithmException - * javax.net.ssl.SSLEngine#getHandshakeStatus() - */ - public void test_getHandshakeStatus() throws NoSuchAlgorithmException { - SSLEngine sse = getEngine(); - try { - assertEquals(sse.getHandshakeStatus().toString(), "NOT_HANDSHAKING"); - sse.setUseClientMode(true); - sse.beginHandshake(); - assertEquals(sse.getHandshakeStatus().toString(), "NEED_WRAP"); - } catch (Exception ex) { - fail("Unexpected exception " + ex); - } - } - - /** - * @throws NoSuchAlgorithmException - * javax.net.ssl.SSLEngine#getDelegatedTask() - */ - @KnownFailure("com.android.org.conscrypt.SSLEngineImpl#getDelegatedTask() throws NPE instead of returning null") - public void test_getDelegatedTask() throws NoSuchAlgorithmException { - SSLEngine sse = getEngine(); - try { - assertNull(sse.getDelegatedTask()); - } catch (Exception ex) { - fail("Unexpected exception " + ex); - } - } - - /** - * @throws IOException - * @throws InterruptedException - * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts, - * int offset, int length) - * Exception case: SSLException should be thrown. - */ - public void test_unwrap_01() throws IOException, InterruptedException { - prepareEngines(); - doHandshake(); - - ByteBuffer bbs = ByteBuffer.wrap(new byte[] {1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,31,2,3,1,2,3,1,2,3,1,2,3}); - ByteBuffer bbd = ByteBuffer.allocate(100); - try { - clientEngine.engine.unwrap(bbs, new ByteBuffer[] { bbd }, 0, 1); - fail("SSLException wasn't thrown"); - } catch (SSLException ex) { - //expected - } - } - - /** - * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts, - * int offset, int length) - * Exception case: IndexOutOfBoundsException should be thrown. - */ - @KnownFailure("Fixed in DonutBurger, boundary checks missing") - public void test_unwrap_02() throws SSLException { - String host = "new host"; - int port = 8080; - ByteBuffer[] bbA = { ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) }; - - ByteBuffer bb = ByteBuffer.allocate(10); - SSLEngine sse = getEngine(host, port); - sse.setUseClientMode(true); - - try { - sse.unwrap(bb, bbA, -1, 3); - fail("IndexOutOfBoundsException wasn't thrown"); - } catch (IndexOutOfBoundsException iobe) { - //expected - } - try { - sse.unwrap(bb, bbA, 0, -3); - fail("IndexOutOfBoundsException wasn't thrown"); - } catch (IndexOutOfBoundsException iobe) { - //expected - } - try { - sse.unwrap(bb, bbA, bbA.length + 1, bbA.length); - fail("IndexOutOfBoundsException wasn't thrown"); - } catch (IndexOutOfBoundsException iobe) { - //expected - } - try { - sse.unwrap(bb, bbA, 0, bbA.length + 1); - fail("IndexOutOfBoundsException wasn't thrown"); - } catch (IndexOutOfBoundsException iobe) { - //expected - } - } - - /** - * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts, - * int offset, int length) - * Exception case: ReadOnlyBufferException should be thrown. - */ - @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown") - public void test_unwrap_03() { - String host = "new host"; - int port = 8080; - ByteBuffer bbR = ByteBuffer.allocate(100).asReadOnlyBuffer(); - ByteBuffer[] bbA = { bbR, ByteBuffer.allocate(10), ByteBuffer.allocate(100) }; - - ByteBuffer bb = ByteBuffer.allocate(10); - SSLEngine sse = getEngine(host, port); - sse.setUseClientMode(true); - - try { - sse.unwrap(bb, bbA, 0, bbA.length); - fail("ReadOnlyBufferException wasn't thrown"); - } catch (ReadOnlyBufferException iobe) { - //expected - } catch (Exception e) { - fail(e + " was thrown instead of ReadOnlyBufferException"); - } - } - - /** - * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts, - * int offset, int length) - * Exception case: IllegalArgumentException should be thrown. - */ - @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown") - public void test_unwrap_04() { - String host = "new host"; - int port = 8080; - ByteBuffer[] bbA = {ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100)}; - ByteBuffer[] bbAN = {ByteBuffer.allocate(100), null, ByteBuffer.allocate(100)}; - ByteBuffer[] bbN = null; - ByteBuffer bb = ByteBuffer.allocate(10); - ByteBuffer bN = null; - SSLEngine sse = getEngine(host, port); - sse.setUseClientMode(true); - - try { - sse.unwrap(bN, bbA, 0, 3); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iobe) { - //expected - } catch (NullPointerException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of IllegalArgumentException"); - } - try { - sse.unwrap(bb, bbAN, 0, 3); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iobe) { - //expected - } catch (NullPointerException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of IllegalArgumentException"); - } - try { - sse.unwrap(bb, bbN, 0, 0); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iobe) { - //expected - } catch (NullPointerException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of IllegalArgumentException"); - } - try { - sse.unwrap(bN, bbN, 0, 0); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iobe) { - //expected - } catch (NullPointerException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of IllegalArgumentException"); - } - - } - - /** - * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts, - * int offset, int length) - * Exception case: IllegalStateException should be thrown. - */ - @AndroidOnly("The RI doesn't throw the IllegalStateException.") - public void test_unwrap_05() { - String host = "new host"; - int port = 8080; - ByteBuffer[] bbA = { ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) }; - - ByteBuffer bb = ByteBuffer.allocate(10); - SSLEngine sse = getEngine(host, port); - - try { - sse.unwrap(bb, bbA, 0, bbA.length); - fail("IllegalStateException wasn't thrown"); - } catch (IllegalStateException iobe) { - //expected - } catch (Exception e) { - fail(e + " was thrown instead of IllegalStateException"); - } - } - - /** - * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts, - * int offset, int length) - */ - public void test_unwrap_06() { - String host = "new host"; - int port = 8080; - ByteBuffer[] bbA = { ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) }; - - ByteBuffer bb = ByteBuffer.allocate(10); - SSLEngine sse = getEngine(host, port); - sse.setUseClientMode(true); - - try { - SSLEngineResult res = sse.unwrap(bb, bbA, 0, bbA.length); - assertEquals(0, res.bytesConsumed()); - assertEquals(0, res.bytesProduced()); - } catch (Exception ex) { - fail("Unexpected exception: " + ex); - } - } - - public void test_wrap_01() throws IOException, InterruptedException { - prepareEngines(); - doHandshake(); - ByteBuffer bbs = ByteBuffer.allocate(100); - ByteBuffer bbd = ByteBuffer.allocate(20000); - clientEngine.engine.wrap(new ByteBuffer[] { bbs }, 0, 1, bbd); - } - - /** - * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, int offset, - * int length, ByteBuffer dst) - * Exception case: IndexOutOfBoundsException should be thrown. - */ - @KnownFailure("Fixed in DonutBurger, boundary checks missing") - public void test_wrap_02() throws SSLException { - String host = "new host"; - int port = 8080; - ByteBuffer bb = ByteBuffer.allocate(10); - ByteBuffer[] bbA = {ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5)}; - SSLEngine sse = getEngine(host, port); - sse.setUseClientMode(true); - - try { - sse.wrap(bbA, -1, 3, bb); - fail("IndexOutOfBoundsException wasn't thrown"); - } catch (IndexOutOfBoundsException iobe) { - //expected - } - try { - sse.wrap(bbA, 0, -3, bb); - fail("IndexOutOfBoundsException wasn't thrown"); - } catch (IndexOutOfBoundsException iobe) { - //expected - } - try { - sse.wrap(bbA, bbA.length + 1, bbA.length, bb); - fail("IndexOutOfBoundsException wasn't thrown"); - } catch (IndexOutOfBoundsException iobe) { - //expected - } - try { - sse.wrap(bbA, 0, bbA.length + 1, bb); - fail("IndexOutOfBoundsException wasn't thrown"); - } catch (IndexOutOfBoundsException iobe) { - //expected - } - } - - /** - * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, int offset, - * int length, ByteBuffer dst) - * Exception case: ReadOnlyBufferException should be thrown. - */ - public void test_wrap_03() throws SSLException { - String host = "new host"; - int port = 8080; - ByteBuffer bb = ByteBuffer.allocate(10).asReadOnlyBuffer(); - ByteBuffer[] bbA = {ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5)}; - SSLEngine sse = getEngine(host, port); - sse.setUseClientMode(true); - - try { - sse.wrap(bbA, 0, bbA.length, bb); - fail("ReadOnlyBufferException wasn't thrown"); - } catch (ReadOnlyBufferException iobe) { - //expected - } - } - - /** - * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, int offset, - * int length, ByteBuffer dst) - * Exception case: IllegalArgumentException should be thrown. - */ - @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown") - public void test_wrap_04() { - String host = "new host"; - int port = 8080; - ByteBuffer[] bbA = {ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100)}; - ByteBuffer[] bbN = null; - ByteBuffer bN = null; - SSLEngine e = getEngine(host, port); - e.setUseClientMode(true); - - try { - e.wrap(bbA, 0, 3, bN); - fail("IllegalArgumentException must be thrown for null srcs byte buffer array"); - } catch (NullPointerException npe) { - } catch (IllegalArgumentException ex) { - } catch (Exception ex) { - fail(ex + " was thrown instead of IllegalArgumentException"); - } - - try { - e.wrap(bbN, 0, 0, bN); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException ex) { - } catch (NullPointerException npe) { - } catch (Exception ex) { - fail(ex + " was thrown instead of IllegalArgumentException"); - } - } - - /** - * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, int offset, - * int length, ByteBuffer dst) - * Exception case: IllegalStateException should be thrown. - */ - @AndroidOnly("The RI doesn't throw the IllegalStateException.") - public void test_wrap_05() throws SSLException { - String host = "new host"; - int port = 8080; - ByteBuffer bb = ByteBuffer.allocate(10); - ByteBuffer[] bbA = {ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5)}; - SSLEngine sse = getEngine(host, port); - - try { - sse.wrap(bbA, 0, bbA.length, bb); - fail("IllegalStateException wasn't thrown"); - } catch (IllegalStateException iobe) { - //expected - } - } - - /** - * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, int offset, - * int length, ByteBuffer dst) - */ - public void test_wrap_06() { - String host = "new host"; - int port = 8080; - ByteBuffer bb = ByteBuffer.allocate(10); - ByteBuffer[] bbA = {ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5)}; - SSLEngine sse = getEngine(host, port); - sse.setUseClientMode(true); - - try { - sse.wrap(bbA, 0, bbA.length, bb); - } catch (Exception ex) { - fail("Unexpected exception: " + ex); - } - } - - /** - * @throws NoSuchAlgorithmException - * javax.net.ssl.SSLEngine#closeOutbound() - * javax.net.ssl.SSLEngine#isOutboundDone() - */ - public void test_closeOutbound() throws NoSuchAlgorithmException { - SSLEngine sse = getEngine(); - - try { - assertFalse(sse.isOutboundDone()); - sse.closeOutbound(); - assertTrue(sse.isOutboundDone()); - } catch (Exception ex) { - fail("Unexpected exception: " + ex); - } - } - - /** - * @throws NoSuchAlgorithmException - * javax.net.ssl.SSLEngine#closeInbound() - * javax.net.ssl.SSLEngine#isInboundDone() - */ - public void test_closeInbound() throws NoSuchAlgorithmException { - SSLEngine sse = getEngine(); - - try { - assertFalse(sse.isInboundDone()); - sse.closeInbound(); - assertTrue(sse.isInboundDone()); - } catch (Exception ex) { - fail("Unexpected exception: " + ex); - } - } - - /** - * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer dst) - * SSLException should be thrown. - */ - public void test_unwrap_ByteBuffer_ByteBuffer_01() throws InterruptedException, IOException { - prepareEngines(); - doHandshake(); - ByteBuffer bbs = ByteBuffer.allocate(100); - ByteBuffer bbd = ByteBuffer.allocate(100); - - try { - SSLEngineResult unwrap = clientEngine.engine.unwrap(bbs, bbd); - fail("SSLException wasn't thrown"); - } catch (SSLException ex) { - //expected - } - } - - /** - * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer dst) - * ReadOnlyBufferException should be thrown. - */ - @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown") - public void test_unwrap_ByteBuffer_ByteBuffer_02() { - String host = "new host"; - int port = 8080; - ByteBuffer bbs = ByteBuffer.allocate(10); - ByteBuffer bbd = ByteBuffer.allocate(100).asReadOnlyBuffer(); - SSLEngine sse = getEngine(host, port); - sse.setUseClientMode(true); - - try { - sse.unwrap(bbs, bbd); - fail("ReadOnlyBufferException wasn't thrown"); - } catch (ReadOnlyBufferException iobe) { - //expected - } catch (Exception e) { - fail(e + " was thrown instead of ReadOnlyBufferException"); - } - } - - /** - * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer dst) - * IllegalArgumentException should be thrown. - */ - @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown") - public void test_unwrap_ByteBuffer_ByteBuffer_03() { - String host = "new host"; - int port = 8080; - ByteBuffer bbsN = null; - ByteBuffer bbdN = null; - ByteBuffer bbs = ByteBuffer.allocate(10); - ByteBuffer bbd = ByteBuffer.allocate(100); - SSLEngine sse = getEngine(host, port); - sse.setUseClientMode(true); - - try { - sse.unwrap(bbsN, bbd); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iae) { - //expected - } catch (NullPointerException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of IllegalArgumentException"); - } - - try { - sse.unwrap(bbs, bbdN); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iae) { - //expected - } catch (NullPointerException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of IllegalArgumentException"); - } - - try { - sse.unwrap(bbsN, bbdN); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iae) { - //expected - } catch (NullPointerException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of IllegalArgumentException"); - } - } - - /** - * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer dst) - * IllegalStateException should be thrown. - */ - @AndroidOnly("The RI doesn't throw the IllegalStateException.") - public void test_unwrap_ByteBuffer_ByteBuffer_04() { - String host = "new host"; - int port = 8080; - ByteBuffer bbs = ByteBuffer.allocate(10); - ByteBuffer bbd = ByteBuffer.allocate(100); - SSLEngine sse = getEngine(host, port); - - try { - sse.unwrap(bbs, bbd); - fail("IllegalStateException wasn't thrown"); - } catch (IllegalStateException iobe) { - //expected - } catch (Exception e) { - fail(e + " was thrown instead of IllegalStateException"); - } - } - - /** - * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer dst) - */ - public void test_unwrap_ByteBuffer_ByteBuffer_05() { - String host = "new host"; - int port = 8080; - ByteBuffer bbs = ByteBuffer.allocate(10); - ByteBuffer bbd = ByteBuffer.allocate(100); - SSLEngine sse = getEngine(host, port); - sse.setUseClientMode(true); - - try { - SSLEngineResult res = sse.unwrap(bbs, bbd); - assertEquals(0, res.bytesConsumed()); - assertEquals(0, res.bytesProduced()); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - } - - /** - * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts) - * SSLException should be thrown. - */ - public void test_unwrap_ByteBuffer$ByteBuffer_01() throws IOException, InterruptedException { - prepareEngines(); - doHandshake(); - - ByteBuffer bbs = ByteBuffer.allocate(100); - ByteBuffer bbd = ByteBuffer.allocate(100); - - try { - clientEngine.engine.unwrap(bbs, new ByteBuffer[] { bbd }); - fail("SSLException wasn't thrown"); - } catch (SSLException ex) { - //expected - } - } - - /** - * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts) - * ReadOnlyBufferException should be thrown. - */ - @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown") - public void test_unwrap_ByteBuffer$ByteBuffer_02() { - String host = "new host"; - int port = 8080; - ByteBuffer bbs = ByteBuffer.allocate(10); - ByteBuffer bbR = ByteBuffer.allocate(100).asReadOnlyBuffer(); - ByteBuffer[] bbA = { bbR, ByteBuffer.allocate(10), ByteBuffer.allocate(100) }; - SSLEngine sse = getEngine(host, port); - sse.setUseClientMode(true); - - try { - sse.unwrap(bbs, bbA); - fail("ReadOnlyBufferException wasn't thrown"); - } catch (ReadOnlyBufferException iobe) { - //expected - } catch (Exception e) { - fail(e + " was thrown instead of ReadOnlyBufferException"); - } - } - - /** - * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts) - * IllegalArgumentException should be thrown. - */ - @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown") - public void test_unwrap_ByteBuffer$ByteBuffer_03() { - String host = "new host"; - int port = 8080; - ByteBuffer[] bbA = { ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) }; - ByteBuffer[] bbN = { ByteBuffer.allocate(100), null, ByteBuffer.allocate(100) }; - ByteBuffer[] bbAN = null; - ByteBuffer bb = ByteBuffer.allocate(10); - ByteBuffer bN = null; - SSLEngine sse = getEngine(host, port); - sse.setUseClientMode(true); - - try { - sse.unwrap(bN, bbA); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iobe) { - //expected - } catch (NullPointerException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of IllegalArgumentException"); - } - - try { - sse.unwrap(bb, bbAN); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iobe) { - //expected - } catch (NullPointerException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of IllegalArgumentException"); - } - - try { - sse.unwrap(bb, bbN); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iobe) { - //expected - } catch (NullPointerException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of IllegalArgumentException"); - } - - try { - sse.unwrap(bN, bbAN); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iobe) { - //expected - } catch (NullPointerException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of IllegalArgumentException"); - } - } - - /** - * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts) - * IllegalStateException should be thrown. - */ - @AndroidOnly("The RI doesn't throw the IllegalStateException.") - public void test_unwrap_ByteBuffer$ByteBuffer_04() { - String host = "new host"; - int port = 8080; - ByteBuffer bbs = ByteBuffer.allocate(10); - ByteBuffer[] bbd = {ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) }; - SSLEngine sse = getEngine(host, port); - - try { - sse.unwrap(bbs, bbd); - fail("IllegalStateException wasn't thrown"); - } catch (IllegalStateException iobe) { - //expected - } catch (Exception e) { - fail(e + " was thrown instead of IllegalStateException"); - } - } - - /** - * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts) - */ - public void test_unwrap_ByteBuffer$ByteBuffer_05() { - String host = "new host"; - int port = 8080; - ByteBuffer bbs = ByteBuffer.allocate(10); - ByteBuffer[] bbd = {ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) }; - SSLEngine sse = getEngine(host, port); - sse.setUseClientMode(true); - - try { - SSLEngineResult res = sse.unwrap(bbs, bbd); - assertEquals(0, res.bytesConsumed()); - assertEquals(0, res.bytesProduced()); - } catch (Exception ex) { - fail("Unexpected exception: " + ex); - } - } - - public void test_wrap_ByteBuffer_ByteBuffer_01() throws IOException, InterruptedException { - prepareEngines(); - doHandshake(); - ByteBuffer bbs = ByteBuffer.allocate(20); - ByteBuffer bbd = ByteBuffer.allocate(20000); - clientEngine.engine.wrap(bbs, bbd); - } - - /** - * javax.net.ssl.SSLEngine#wrap(ByteBuffer src, ByteBuffer dst) - * ReadOnlyBufferException should be thrown. - */ - public void test_wrap_ByteBuffer_ByteBuffer_02() { - String host = "new host"; - int port = 8080; - ByteBuffer bbs = ByteBuffer.allocate(10); - ByteBuffer bbd = ByteBuffer.allocate(100).asReadOnlyBuffer(); - SSLEngine sse = getEngine(host, port); - sse.setUseClientMode(true); - - try { - sse.wrap(bbs, bbd); - fail("ReadOnlyBufferException wasn't thrown"); - } catch (ReadOnlyBufferException iobe) { - //expected - } catch (Exception e) { - fail(e + " was thrown instead of ReadOnlyBufferException"); - } - } - - /** - * javax.net.ssl.SSLEngine#wrap(ByteBuffer src, ByteBuffer dst) - * IllegalArgumentException should be thrown. - */ - @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown") - public void test_wrap_ByteBuffer_ByteBuffer_03() { - String host = "new host"; - int port = 8080; - ByteBuffer bbsN = null; - ByteBuffer bbdN = null; - ByteBuffer bbs = ByteBuffer.allocate(10); - ByteBuffer bbd = ByteBuffer.allocate(100); - SSLEngine sse = getEngine(host, port); - sse.setUseClientMode(true); - - try { - sse.wrap(bbsN, bbd); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iae) { - //expected - } catch (NullPointerException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of IllegalArgumentException"); - } - - try { - sse.wrap(bbs, bbdN); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iae) { - //expected - } catch (NullPointerException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of IllegalArgumentException"); - } - - try { - sse.wrap(bbsN, bbdN); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iae) { - //expected - } catch (NullPointerException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of IllegalArgumentException"); - } - } - - /** - * javax.net.ssl.SSLEngine#wrap(ByteBuffer src, ByteBuffer dst) - * IllegalStateException should be thrown. - */ - @AndroidOnly("The RI doesn't throw the IllegalStateException.") - public void test_wrap_ByteBuffer_ByteBuffer_04() { - String host = "new host"; - int port = 8080; - ByteBuffer bbs = ByteBuffer.allocate(10); - ByteBuffer bbd = ByteBuffer.allocate(10); - SSLEngine sse = getEngine(host, port); - - try { - sse.wrap(bbs, bbd); - fail("IllegalStateException wasn't thrown"); - } catch (IllegalStateException iobe) { - //expected - } catch (Exception e) { - fail(e + " was thrown instead of IllegalStateException"); - } - } - - /** - * javax.net.ssl.SSLEngine#wrap(ByteBuffer src, ByteBuffer dst) - */ - public void test_wrap_ByteBuffer_ByteBuffer_05() { - String host = "new host"; - int port = 8080; - ByteBuffer bb = ByteBuffer.allocate(10); - SSLEngine sse = getEngine(host, port); - sse.setUseClientMode(true); - - try { - SSLEngineResult res = sse.wrap(bb, ByteBuffer.allocate(10)); - assertEquals(0, res.bytesConsumed()); - assertEquals(0, res.bytesProduced()); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - } - - /** - * @throws IOException - * @throws InterruptedException - * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, ByteBuffer dst) - * SSLException should be thrown. - */ - public void test_wrap_ByteBuffer$ByteBuffer_01() throws IOException, InterruptedException { - prepareEngines(); - doHandshake(); - ByteBuffer bbs = ByteBuffer.allocate(100); - ByteBuffer bbd = ByteBuffer.allocate(20000); - - try { - clientEngine.engine.wrap(new ByteBuffer[] { bbs }, bbd); - serverEngine.engine.wrap(new ByteBuffer[] { bbs }, bbd); - //fail("SSLException wasn't thrown"); - } catch (SSLException ex) { - //expected - } - } - - /** - * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, ByteBuffer dst) - * ReadOnlyBufferException should be thrown. - */ - public void test_wrap_ByteBuffer$ByteBuffer_02() { - String host = "new host"; - int port = 8080; - ByteBuffer bb = ByteBuffer.allocate(10).asReadOnlyBuffer(); - ByteBuffer[] bbA = {ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5)}; - SSLEngine sse = getEngine(host, port); - sse.setUseClientMode(true); - - try { - sse.wrap(bbA, bb); - fail("ReadOnlyBufferException wasn't thrown"); - } catch (ReadOnlyBufferException iobe) { - //expected - } catch (Exception e) { - fail(e + " was thrown instead of ReadOnlyBufferException"); - } - } - - /** - * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, ByteBuffer dst) - * IllegalArgumentException should be thrown. - */ - @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown") - public void test_wrap_ByteBuffer$ByteBuffer_03() { - String host = "new host"; - int port = 8080; - ByteBuffer[] bbA = {ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100)}; - ByteBuffer[] bbAN = null; - ByteBuffer bb = ByteBuffer.allocate(10); - ByteBuffer bN = null; - SSLEngine sse = getEngine(host, port); - sse.setUseClientMode(true); - - try { - sse.wrap(bbA, bN); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iobe) { - //expected - } catch (NullPointerException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of IllegalArgumentException"); - } - - try { - sse.wrap(bbAN, bb); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iobe) { - //expected - } catch (NullPointerException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of IllegalArgumentException"); - } - - try { - sse.wrap(bbAN, bN); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iobe) { - //expected - } catch (NullPointerException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of IllegalArgumentException"); - } - } - - /** - * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, ByteBuffer dst) - * IllegalStateException should be thrown. - */ - @AndroidOnly("The RI doesn't throw the IllegalStateException.") - public void test_wrap_ByteBuffer$ByteBuffer_04() { - String host = "new host"; - int port = 8080; - ByteBuffer bb = ByteBuffer.allocate(10); - ByteBuffer[] bbA = { ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5) }; - SSLEngine sse = getEngine(host, port); - - try { - sse.wrap(bbA, bb); - fail("IllegalStateException wasn't thrown"); - } catch (IllegalStateException iobe) { - //expected - } catch (Exception e) { - fail(e + " was thrown instead of IllegalStateException"); - } - } - - /** - * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, ByteBuffer dst) - */ - public void test_wrap_ByteBuffer$ByteBuffer_05() { - String host = "new host"; - int port = 8080; - ByteBuffer bb = ByteBuffer.allocate(10); - ByteBuffer[] bbA = { ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5) }; - SSLEngine sse = getEngine(host, port); - sse.setUseClientMode(true); - - try { - SSLEngineResult res = sse.wrap(bbA, bb); - assertEquals(0, res.bytesConsumed()); - assertEquals(0, res.bytesProduced()); - } catch (Exception ex) { - fail("Unexpected exception: " + ex); - } - } - - private SSLEngine getEngine() { - SSLContext context = null; - try { - context = SSLContext.getInstance("TLS"); - context.init(null, null, null); - } catch (KeyManagementException e) { - fail("Could not get SSLEngine: key management exception " - + e.getMessage()); - } catch (NoSuchAlgorithmException e) { - fail("Could not get SSLEngine: no such algorithm " + e.getMessage()); - } - return context.createSSLEngine(); - } - - private SSLEngine getEngine(String host, int port) { - SSLContext context = null; - try { - context = SSLContext.getInstance("TLS"); - context.init(null, null, null); - } catch (KeyManagementException e) { - fail("Could not get SSLEngine: key management exception " - + e.getMessage()); - } catch (NoSuchAlgorithmException e) { - fail("Could not get SSLEngine: no such algorithm " + e.getMessage()); - } - return context.createSSLEngine(host, port); - } - - class HandshakeHandler implements Runnable { - - private final SSLEngine engine; - - private final SourceChannel in; - - private final SinkChannel out; - - private final ByteBuffer EMPTY = ByteBuffer.allocate(0); - - @SuppressWarnings("unused") - private final String LOGTAG; - - private SSLEngineResult.HandshakeStatus status; - - private ByteBuffer readBuffer; - - private ByteBuffer writeBuffer; - - HandshakeHandler(boolean clientMode, SourceChannel in, SinkChannel out) - throws SSLException { - this.in = in; - this.out = out; - engine = getEngine(); - engine.setUseClientMode(clientMode); - String[] cipherSuites = engine.getSupportedCipherSuites(); - Set<String> enabledSuites = new HashSet<String>(); - for (String cipherSuite : cipherSuites) { - if (cipherSuite.contains("anon")) { - enabledSuites.add(cipherSuite); - } - } - engine.setEnabledCipherSuites((String[]) enabledSuites.toArray( - new String[enabledSuites.size()])); - - engine.beginHandshake(); - status = engine.getHandshakeStatus(); - - if (clientMode) { - LOGTAG = "CLIENT: "; - } else { - LOGTAG = "SERVER: "; - } - - log("CipherSuites: " + Arrays.toString(engine.getEnabledCipherSuites())); - log(status); - - readBuffer = ByteBuffer.allocate(200000); - writeBuffer = ByteBuffer.allocate(20000); - } - - public SSLEngineResult.HandshakeStatus getStatus() { - return status; - } - - private void log(Object o) { - //System.out.print(LOGTAG); - //System.out.println(o); - } - - private ByteBuffer read() throws IOException { - if (readBuffer == null || readBuffer.remaining() == 0 || readBuffer.position() == 0) { - readBuffer.clear(); - int read = in.read(readBuffer); - log("read: " + read); - readBuffer.rewind(); - readBuffer.limit(read); - } - return readBuffer; - } - - public void run() { - try { - while (true) { - switch (status) { - case FINISHED: { - log(status); - return; - } - case NEED_TASK: { - log(status); - Runnable task; - while ((task = engine.getDelegatedTask()) != null) { - task.run(); - } - status = engine.getHandshakeStatus(); - break; - } - case NEED_UNWRAP: { - log(status); - ByteBuffer source = read(); - writeBuffer.clear(); - - while (status == HandshakeStatus.NEED_UNWRAP) { - SSLEngineResult result = engine.unwrap(source, writeBuffer); - status = result.getHandshakeStatus(); - log(result); - } - break; - } - case NEED_WRAP: { - log(status); - writeBuffer.clear(); - - int produced = 0; - SSLEngineResult result = null; - while (status == HandshakeStatus.NEED_WRAP) { - result = engine.wrap(EMPTY, writeBuffer); - status = result.getHandshakeStatus(); - produced += result.bytesProduced(); - log(result); - } - writeBuffer.rewind(); - writeBuffer.limit(produced); - log("write: " + produced); - out.write(writeBuffer); - break; - } - case NOT_HANDSHAKING: { - log("Not Handshaking"); - return; - } - } - } - } catch (IOException e) { - log(e); - } catch (RuntimeException e) { - // ignore; - } - } - } - - @KnownFailure("Handshake Status is never finished. NPE in " - + "ClientSessionContext$HostAndPort.hashCode() when host is null") - public void testHandshake() throws IOException, InterruptedException { - - prepareEngines(); - - assertTrue("handshake failed", doHandshake()); - - System.out.println(clientEngine.engine.getSession().getCipherSuite()); - - assertEquals("Handshake not finished", - SSLEngineResult.HandshakeStatus.FINISHED, - clientEngine.getStatus()); - assertEquals("Handshake not finished", - SSLEngineResult.HandshakeStatus.FINISHED, - serverEngine.getStatus()); - } - - void prepareEngines() throws IOException { - Pipe clientSendPipe = Pipe.open(); - Pipe serverSendPipe = Pipe.open(); - - SinkChannel clientSink = clientSendPipe.sink(); - SourceChannel serverSource = clientSendPipe.source(); - SinkChannel serverSink = serverSendPipe.sink(); - SourceChannel clientSource = serverSendPipe.source(); - - clientEngine = new HandshakeHandler(true, clientSource, clientSink); - serverEngine = new HandshakeHandler(false, serverSource, serverSink); - } - - boolean doHandshake() throws InterruptedException { - Thread clientThread = new Thread(clientEngine); - clientThread.start(); - - Thread serverThread = new Thread(serverEngine); - serverThread.start(); - - int i = 0; - while (clientThread.isAlive() && serverThread.isAlive() && i < 20) { - Thread.sleep(500); - i++; - } - - if (clientThread.isAlive()) { - clientThread.interrupt(); - } - - if (serverThread.isAlive()) { - serverThread.interrupt(); - } - - return clientEngine.getStatus() == HandshakeStatus.FINISHED && serverEngine.getStatus() == HandshakeStatus.FINISHED; - } - -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLExceptionTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLExceptionTest.java deleted file mode 100644 index 9b4ae35..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/SSLExceptionTest.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.net.ssl; - -import javax.net.ssl.SSLException; - -import junit.framework.TestCase; - -/** - * Tests for <code>SSLException</code> class constructors and methods. - * - */ -public class SSLExceptionTest extends TestCase { - - private static String[] msgs = { - "", - "Check new message", - "Check new message Check new message Check new message Check new message Check new message" }; - - private static Throwable tCause = new Throwable("Throwable for exception"); - - /** - * Test for <code>SSLException(String)</code> constructor Assertion: - * constructs SSLException with detail message msg. Parameter - * <code>msg</code> is not null. - */ - public void testSSLException01() { - SSLException sE; - for (int i = 0; i < msgs.length; i++) { - sE = new SSLException(msgs[i]); - assertEquals("getMessage() must return: ".concat(msgs[i]), sE.getMessage(), msgs[i]); - assertNull("getCause() must return null", sE.getCause()); - } - } - - /** - * Test for <code>SSLException(String)</code> constructor Assertion: - * constructs SSLException when <code>msg</code> is null - */ - public void testSSLException02() { - String msg = null; - SSLException sE = new SSLException(msg); - assertNull("getMessage() must return null.", sE.getMessage()); - assertNull("getCause() must return null", sE.getCause()); - } - - /** - * Test for <code>SSLException(Throwable)</code> constructor - * Assertion: constructs SSLException when <code>cause</code> is null - */ - public void testSSLException03() { - Throwable cause = null; - SSLException sE = new SSLException(cause); - assertNull("getMessage() must return null.", sE.getMessage()); - assertNull("getCause() must return null", sE.getCause()); - } - - /** - * Test for <code>SSLException(Throwable)</code> constructor - * Assertion: constructs SSLException when <code>cause</code> is not - * null - */ - public void testSSLException04() { - SSLException sE = new SSLException(tCause); - if (sE.getMessage() != null) { - String toS = tCause.toString(); - String getM = sE.getMessage(); - assertTrue("getMessage() should contain ".concat(toS), (getM - .indexOf(toS) != -1)); - } - assertNotNull("getCause() must not return null", sE.getCause()); - assertEquals("getCause() must return ".concat(tCause.toString()), sE.getCause(), tCause); - } - - /** - * Test for <code>SSLException(String, Throwable)</code> constructor - * Assertion: constructs SSLException when <code>cause</code> is null - * <code>msg</code> is null - */ - public void testSSLException05() { - SSLException sE = new SSLException(null, null); - assertNull("getMessage() must return null", sE.getMessage()); - assertNull("getCause() must return null", sE.getCause()); - } - - /** - * Test for <code>SSLException(String, Throwable)</code> constructor - * Assertion: constructs SSLException when <code>cause</code> is null - * <code>msg</code> is not null - */ - public void testSSLException06() { - SSLException sE; - for (int i = 0; i < msgs.length; i++) { - sE = new SSLException(msgs[i], null); - assertEquals("getMessage() must return: ".concat(msgs[i]), sE - .getMessage(), msgs[i]); - assertNull("getCause() must return null", sE.getCause()); - } - } - - /** - * Test for <code>SSLException(String, Throwable)</code> constructor - * Assertion: constructs SSLException when <code>cause</code> is not - * null <code>msg</code> is null - */ - public void testSSLException07() { - SSLException sE = new SSLException(null, tCause); - if (sE.getMessage() != null) { - String toS = tCause.toString(); - String getM = sE.getMessage(); - assertTrue("getMessage() must should ".concat(toS), (getM - .indexOf(toS) != -1)); - } - assertNotNull("getCause() must not return null", sE.getCause()); - assertEquals("getCause() must return ".concat(tCause.toString()), sE - .getCause(), tCause); - } - - /** - * Test for <code>SSLException(String, Throwable)</code> constructor - * Assertion: constructs SSLException when <code>cause</code> is not - * null <code>msg</code> is not null - */ - public void testSSLException08() { - SSLException sE; - for (int i = 0; i < msgs.length; i++) { - sE = new SSLException(msgs[i], tCause); - String getM = sE.getMessage(); - String toS = tCause.toString(); - if (msgs[i].length() > 0) { - assertTrue("getMessage() must contain ".concat(msgs[i]), getM - .indexOf(msgs[i]) != -1); - if (!getM.equals(msgs[i])) { - assertTrue("getMessage() should contain ".concat(toS), getM - .indexOf(toS) != -1); - } - } - assertNotNull("getCause() must not return null", sE.getCause()); - assertEquals("getCause() must return ".concat(tCause.toString()), - sE.getCause(), tCause); - } - } -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLHandshakeExceptionTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLHandshakeExceptionTest.java deleted file mode 100644 index a2d0ec5..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/SSLHandshakeExceptionTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.javax.net.ssl; - -import javax.net.ssl.SSLHandshakeException; - -import junit.framework.TestCase; - -public class SSLHandshakeExceptionTest extends TestCase { - - private static String[] msgs = { - "", - "Check new message", - "Check new message Check new message Check new message Check new message Check new message" }; - - - /** - * Test for <code>SSLHandshakeException(String)</code> constructor Assertion: - * constructs SSLHandshakeException with detail message msg. Parameter - * <code>msg</code> is not null. - */ - public void test_Constructor01() { - SSLHandshakeException sslE; - for (int i = 0; i < msgs.length; i++) { - sslE = new SSLHandshakeException(msgs[i]); - assertEquals("getMessage() must return: ".concat(msgs[i]), sslE.getMessage(), msgs[i]); - assertNull("getCause() must return null", sslE.getCause()); - } - } - - /** - * Test for <code>SSLHandshakeException(String)</code> constructor Assertion: - * constructs SSLHandshakeException with detail message msg. Parameter - * <code>msg</code> is null. - */ - public void test_Constructor02() { - String msg = null; - SSLHandshakeException sslE = new SSLHandshakeException(msg); - assertNull("getMessage() must return null.", sslE.getMessage()); - assertNull("getCause() must return null", sslE.getCause()); - } -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLKeyExceptionTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLKeyExceptionTest.java deleted file mode 100644 index d6ba998..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/SSLKeyExceptionTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.javax.net.ssl; - -import javax.net.ssl.SSLKeyException; - -import junit.framework.TestCase; - -public class SSLKeyExceptionTest extends TestCase { - - private static String[] msgs = { - "", - "Check new message", - "Check new message Check new message Check new message Check new message Check new message" }; - - - /** - * Test for <code>SSLKeyException(String)</code> constructor Assertion: - * constructs SSLKeyException with detail message msg. Parameter - * <code>msg</code> is not null. - */ - public void test_Constructor01() { - SSLKeyException skE; - for (int i = 0; i < msgs.length; i++) { - skE = new SSLKeyException(msgs[i]); - assertEquals("getMessage() must return: ".concat(msgs[i]), skE.getMessage(), msgs[i]); - assertNull("getCause() must return null", skE.getCause()); - } - } - - /** - * Test for <code>SSLPeerUnverifiedException(String)</code> constructor Assertion: - * constructs SSLPeerUnverifiedException with detail message msg. Parameter - * <code>msg</code> is null. - */ - public void test_Constructor02() { - String msg = null; - SSLKeyException skE = new SSLKeyException(msg); - assertNull("getMessage() must return null.", skE.getMessage()); - assertNull("getCause() must return null", skE.getCause()); - } -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLPeerUnverifiedExceptionTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLPeerUnverifiedExceptionTest.java deleted file mode 100644 index a8b9ac4..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/SSLPeerUnverifiedExceptionTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.javax.net.ssl; - -import javax.net.ssl.SSLPeerUnverifiedException; - -import junit.framework.TestCase; - -public class SSLPeerUnverifiedExceptionTest extends TestCase { - - private static String[] msgs = { - "", - "Check new message", - "Check new message Check new message Check new message Check new message Check new message" }; - - - /** - * Test for <code>SSLPeerUnverifiedException(String)</code> constructor Assertion: - * constructs SSLPeerUnverifiedException with detail message msg. Parameter - * <code>msg</code> is not null. - */ - public void test_Constructor01() { - SSLPeerUnverifiedException sslE; - for (int i = 0; i < msgs.length; i++) { - sslE = new SSLPeerUnverifiedException(msgs[i]); - assertEquals("getMessage() must return: ".concat(msgs[i]), sslE.getMessage(), msgs[i]); - assertNull("getCause() must return null", sslE.getCause()); - } - } - - /** - * Test for <code>SSLPeerUnverifiedException(String)</code> constructor Assertion: - * constructs SSLPeerUnverifiedException with detail message msg. Parameter - * <code>msg</code> is null. - */ - public void test_Constructor02() { - String msg = null; - SSLPeerUnverifiedException sslE = new SSLPeerUnverifiedException(msg); - assertNull("getMessage() must return null.", sslE.getMessage()); - assertNull("getCause() must return null", sslE.getCause()); - } -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLProtocolExceptionTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLProtocolExceptionTest.java deleted file mode 100644 index 14b562d..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/SSLProtocolExceptionTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.javax.net.ssl; - -import javax.net.ssl.SSLProtocolException; - -import junit.framework.TestCase; - -public class SSLProtocolExceptionTest extends TestCase { - - private static String[] msgs = { - "", - "Check new message", - "Check new message Check new message Check new message Check new message Check new message" }; - - - /** - * Test for <code>SSLProtocolException(String)</code> constructor Assertion: - * constructs SSLProtocolException with detail message msg. Parameter - * <code>msg</code> is not null. - */ - public void test_Constructor01() { - SSLProtocolException sslE; - for (int i = 0; i < msgs.length; i++) { - sslE = new SSLProtocolException(msgs[i]); - assertEquals("getMessage() must return: ".concat(msgs[i]), sslE.getMessage(), msgs[i]); - assertNull("getCause() must return null", sslE.getCause()); - } - } - - /** - * Test for <code>SSLProtocolException(String)</code> constructor Assertion: - * constructs SSLProtocolException with detail message msg. Parameter - * <code>msg</code> is null. - */ - public void test_Constructor02() { - String msg = null; - SSLProtocolException sslE = new SSLProtocolException(msg); - assertNull("getMessage() must return null.", sslE.getMessage()); - assertNull("getCause() must return null", sslE.getCause()); - } -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLServerSocketFactoryTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLServerSocketFactoryTest.java deleted file mode 100644 index 5958ecb..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/SSLServerSocketFactoryTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.javax.net.ssl; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.ServerSocket; - -import javax.net.ssl.SSLServerSocketFactory; - -import junit.framework.TestCase; - -public class SSLServerSocketFactoryTest extends TestCase { - - private class MockSSLServerSocketFactory extends SSLServerSocketFactory { - public MockSSLServerSocketFactory() { - super(); - } - - @Override - public String[] getDefaultCipherSuites() { - return null; - } - - @Override - public String[] getSupportedCipherSuites() { - return null; - } - - @Override - public ServerSocket createServerSocket(int arg0) throws IOException { - return null; - } - - @Override - public ServerSocket createServerSocket(int arg0, int arg1) - throws IOException { - return null; - } - - @Override - public ServerSocket createServerSocket(int arg0, int arg1, - InetAddress arg2) throws IOException { - return null; - } - } - - /** - * javax.net.ssl.SSLServerSocketFactory#SSLServerSocketFactory() - */ - public void test_Constructor() { - try { - MockSSLServerSocketFactory ssf = new MockSSLServerSocketFactory(); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - /** - * javax.net.ssl.SSLServerSocketFactory#getDefault() - */ - public void test_getDefault() { - assertNotNull("Incorrect default socket factory", - SSLServerSocketFactory.getDefault()); - } - - /** - * javax.net.ssl.SSLServerSocketFactory#getDefaultCipherSuites() - */ - public void test_getDefaultCipherSuites() { - SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory - .getDefault(); - try { - assertTrue(ssf.getDefaultCipherSuites().length > 0); - } catch (Exception e) { - fail("Unexpected exception " + e); - } - } - - /** - * javax.net.ssl.SSLServerSocketFactory#getSupportedCipherSuites() - */ - public void test_getSupportedCipherSuites() { - SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory - .getDefault(); - try { - assertTrue(ssf.getSupportedCipherSuites().length > 0); - } catch (Exception e) { - fail("Unexpected exception " + e); - } - } -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLServerSocketTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLServerSocketTest.java deleted file mode 100644 index 5086f65..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/SSLServerSocketTest.java +++ /dev/null @@ -1,431 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.javax.net.ssl; - -import junit.framework.TestCase; - -import libcore.io.Base64; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.InetAddress; -import java.security.KeyStore; -import java.security.SecureRandom; -import java.util.Arrays; - -import javax.net.ssl.KeyManager; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLServerSocket; - -public class SSLServerSocketTest extends TestCase { - - // set to true if on Android, false if on RI - boolean useBKS = true; - - /** - * Additional class for SSLServerSocket constructor verification - */ - class mySSLServerSocket extends SSLServerSocket { - - public mySSLServerSocket() throws IOException{ - super(); - } - - public mySSLServerSocket(int port) throws IOException{ - super(port); - } - - public mySSLServerSocket(int port, int backlog) throws IOException{ - super(port, backlog); - } - - public mySSLServerSocket(int port, int backlog, InetAddress address) throws IOException{ - super(port, backlog, address); - } - - public String[] getSupportedCipherSuites() { - return null; - } - - public void setEnabledCipherSuites(String[] suites) { - - } - - public String[] getEnabledCipherSuites() { - return null; - } - - public String[] getSupportedProtocols() { - return null; - } - - public String[] getEnabledProtocols() { - return null; - } - - public void setEnabledProtocols(String[] protocols) { - - } - - public void setEnableSessionCreation(boolean flag) { - - } - - public boolean getEnableSessionCreation() { - return false; - } - - public void setNeedClientAuth(boolean need) { - - } - - public boolean getNeedClientAuth() { - return false; - } - - public boolean getUseClientMode() { - return false; - } - - public void setUseClientMode(boolean mode) { - - } - - public boolean getWantClientAuth() { - return false; - } - public void setWantClientAuth(boolean mode) { - - } - } - - /** - * javax.net.ssl.SSLServerSocket#SSLServerSocket() - */ - public void testConstructor() throws Exception { - SSLServerSocket ssl = new mySSLServerSocket(); - } - - /** - * javax.net.ssl.SSLServerSocket#SSLServerSocket(int port) - */ - public void testConstructor_I() throws Exception { - int[] port_invalid = {-1, 65536, Integer.MIN_VALUE, Integer.MAX_VALUE}; - - SSLServerSocket ssl = new mySSLServerSocket(0); - - for (int i = 0; i < port_invalid.length; i++) { - try { - new mySSLServerSocket(port_invalid[i]); - fail("IllegalArgumentException should be thrown"); - } catch (IllegalArgumentException expected) { - } - } - - try { - new mySSLServerSocket(ssl.getLocalPort()); - fail("IOException Expected when opening an already opened port"); - } catch (IOException expected) { - } - } - - /** - * javax.net.ssl.SSLServerSocket#SSLServerSocket(int port, int backlog) - */ - public void testConstructor_II() throws Exception { - mySSLServerSocket ssl = new mySSLServerSocket(0, 1); - int[] port_invalid = {-1, Integer.MIN_VALUE, Integer.MAX_VALUE}; - - for (int i = 0; i < port_invalid.length; i++) { - try { - new mySSLServerSocket(port_invalid[i], 1); - fail("IllegalArgumentException should be thrown"); - } catch (IllegalArgumentException expected) { - } - } - - try { - new mySSLServerSocket(ssl.getLocalPort(), 1); - fail("IOException should be thrown"); - } catch (IOException expected) { - } - } - - /** - * javax.net.ssl.SSLServerSocket#SSLServerSocket(int port, int backlog, InetAddress address) - */ - public void testConstructor_IIInetAddress() throws Exception { - // A null InetAddress is okay. - new mySSLServerSocket(0, 0, null); - - int[] port_invalid = {-1, 65536, Integer.MIN_VALUE, Integer.MAX_VALUE}; - - mySSLServerSocket ssl = new mySSLServerSocket(0, 0, InetAddress.getLocalHost()); - - for (int i = 0; i < port_invalid.length; i++) { - try { - new mySSLServerSocket(port_invalid[i], 1, InetAddress.getLocalHost()); - fail("IllegalArgumentException should be thrown"); - } catch (IllegalArgumentException expected) { - } - } - - try { - new mySSLServerSocket(ssl.getLocalPort(), 0, InetAddress.getLocalHost()); - fail("IOException should be thrown for"); - } catch (IOException expected) { - } - } - - /** - * @throws Exception - * javax.net.ssl.SSLServerSocket#getSupportedCipherSuites() - */ - public void test_getSupportedCipherSuites() throws Exception { - SSLServerSocket sss = getSSLServerSocket(); - String[] res = sss.getSupportedCipherSuites(); - assertNotNull("NULL result", res); - assertTrue("no supported cipher suites available.", res.length > 0); - } - - /** - * @throws IOException - * javax.net.ssl.SSLServerSocket#getEnabledCipherSuites() - * javax.net.ssl.SSLServerSocket#setEnabledCipherSuites(String[] suites) - */ - public void test_EnabledCipherSuites() throws Exception { - SSLServerSocket sss = getSSLServerSocket(); - try { - sss.setEnabledCipherSuites(null); - } catch (IllegalArgumentException iae) { - //expected - } - String[] unsupportedCipherSuites = {"unsupported"}; - try { - sss.setEnabledCipherSuites(unsupportedCipherSuites); - } catch (IllegalArgumentException iae) { - //expected - } - int count = sss.getSupportedCipherSuites().length; - assertTrue("No supported cipher suites", count > 0); - sss.setEnabledCipherSuites(sss.getSupportedCipherSuites()); - String[] res = sss.getEnabledCipherSuites(); - assertNotNull("NULL result", res); - assertEquals("not all supported cipher suites were enabled", - Arrays.asList(sss.getSupportedCipherSuites()), - Arrays.asList(res)); - } - - /** - * @throws IOException - * javax.net.ssl.SSLServerSocket#getSupportedProtocols() - */ - public void test_getSupportedProtocols() throws Exception { - SSLServerSocket sss = getSSLServerSocket(); - String[] res = sss.getSupportedCipherSuites(); - assertNotNull("NULL result", res); - assertTrue("no supported protocols available.", res.length > 0); - } - - /** - * @throws IOException - * javax.net.ssl.SSLServerSocket#getEnabledProtocols() - * javax.net.ssl.SSLServerSocket#setEnabledProtocols(String[] protocols) - */ - public void test_EnabledProtocols() throws Exception { - SSLServerSocket sss = getSSLServerSocket(); - try { - sss.setEnabledProtocols(null); - } catch (IllegalArgumentException iae) { - //expected - } - String[] unsupportedProtocols = {"unsupported"}; - try { - sss.setEnabledProtocols(unsupportedProtocols); - } catch (IllegalArgumentException iae) { - //expected - } - int count = sss.getSupportedProtocols().length; - assertTrue("No supported protocols", count > 0); - sss.setEnabledProtocols(sss.getSupportedProtocols()); - String[] res = sss.getEnabledProtocols(); - assertNotNull("NULL result", res); - assertTrue("no enabled protocols.", res.length == count); - } - - /** - * @throws IOException - * javax.net.ssl.SSLServerSocket#setEnableSessionCreation(boolean flag) - * javax.net.ssl.SSLServerSocket#getEnableSessionCreation() - */ - public void test_EnableSessionCreation() throws Exception { - SSLServerSocket sss = getSSLServerSocket(); - assertTrue(sss.getEnableSessionCreation()); - sss.setEnableSessionCreation(false); - assertFalse(sss.getEnableSessionCreation()); - sss.setEnableSessionCreation(true); - assertTrue(sss.getEnableSessionCreation()); - } - - /** - * @throws IOException - * javax.net.ssl.SSLServerSocket#setNeedClientAuth(boolean need) - * javax.net.ssl.SSLServerSocket#getNeedClientAuthCreation() - */ - public void test_NeedClientAuth() throws Exception { - SSLServerSocket sss = getSSLServerSocket(); - sss.setNeedClientAuth(true); - assertTrue(sss.getNeedClientAuth()); - sss.setNeedClientAuth(false); - assertFalse(sss.getNeedClientAuth()); - } - - /** - * @throws IOException - * javax.net.ssl.SSLServerSocket#getUseClientMode() - * javax.net.ssl.SSLServerSocket#setUseClientMode(boolean mode) - */ - public void test_UseClientMode() throws Exception { - SSLServerSocket sss = getSSLServerSocket(); - sss.setUseClientMode(false); - assertFalse(sss.getUseClientMode()); - sss.setUseClientMode(true); - assertTrue(sss.getUseClientMode()); - } - - /** - * @throws IOException - * javax.net.ssl.SSLServerSocket#setWantClientAuth(boolean want) - * javax.net.ssl.SSLServerSocket#getWantClientAuthCreation() - */ - public void test_WantClientAuth() throws Exception { - SSLServerSocket sss = getSSLServerSocket(); - sss.setWantClientAuth(true); - assertTrue(sss.getWantClientAuth()); - sss.setWantClientAuth(false); - assertFalse(sss.getWantClientAuth()); - } - - - /** - * Defines the keystore contents for the server, BKS version. Holds just a - * single self-generated key. The subject name is "Test Server". - */ - private static final String SERVER_KEYS_BKS = - "AAAAAQAAABQDkebzoP1XwqyWKRCJEpn/t8dqIQAABDkEAAVteWtleQAAARpYl20nAAAAAQAFWC41" + - "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU1jANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET" + - "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV" + - "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMB4XDTA4MDYwNTExNTgxNFoXDTA4MDkw" + - "MzExNTgxNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U" + - "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IFNlcnZl" + - "cjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0LIdKaIr9/vsTq8BZlA3R+NFWRaH4lGsTAQy" + - "DPMF9ZqEDOaL6DJuu0colSBBBQ85hQTPa9m9nyJoN3pEi1hgamqOvQIWcXBk+SOpUGRZZFXwniJV" + - "zDKU5nE9MYgn2B9AoiH3CSuMz6HRqgVaqtppIe1jhukMc/kHVJvlKRNy9XMCAwEAATANBgkqhkiG" + - "9w0BAQUFAAOBgQC7yBmJ9O/eWDGtSH9BH0R3dh2NdST3W9hNZ8hIa8U8klhNHbUCSSktZmZkvbPU" + - "hse5LI3dh6RyNDuqDrbYwcqzKbFJaq/jX9kCoeb3vgbQElMRX8D2ID1vRjxwlALFISrtaN4VpWzV" + - "yeoHPW4xldeZmoVtjn8zXNzQhLuBqX2MmAAAAqwAAAAUvkUScfw9yCSmALruURNmtBai7kQAAAZx" + - "4Jmijxs/l8EBaleaUru6EOPioWkUAEVWCxjM/TxbGHOi2VMsQWqRr/DZ3wsDmtQgw3QTrUK666sR" + - "MBnbqdnyCyvM1J2V1xxLXPUeRBmR2CXorYGF9Dye7NkgVdfA+9g9L/0Au6Ugn+2Cj5leoIgkgApN" + - "vuEcZegFlNOUPVEs3SlBgUF1BY6OBM0UBHTPwGGxFBBcetcuMRbUnu65vyDG0pslT59qpaR0TMVs" + - "P+tcheEzhyjbfM32/vwhnL9dBEgM8qMt0sqF6itNOQU/F4WGkK2Cm2v4CYEyKYw325fEhzTXosck" + - "MhbqmcyLab8EPceWF3dweoUT76+jEZx8lV2dapR+CmczQI43tV9btsd1xiBbBHAKvymm9Ep9bPzM" + - "J0MQi+OtURL9Lxke/70/MRueqbPeUlOaGvANTmXQD2OnW7PISwJ9lpeLfTG0LcqkoqkbtLKQLYHI" + - "rQfV5j0j+wmvmpMxzjN3uvNajLa4zQ8l0Eok9SFaRr2RL0gN8Q2JegfOL4pUiHPsh64WWya2NB7f" + - "V+1s65eA5ospXYsShRjo046QhGTmymwXXzdzuxu8IlnTEont6P4+J+GsWk6cldGbl20hctuUKzyx" + - "OptjEPOKejV60iDCYGmHbCWAzQ8h5MILV82IclzNViZmzAapeeCnexhpXhWTs+xDEYSKEiG/camt" + - "bhmZc3BcyVJrW23PktSfpBQ6D8ZxoMfF0L7V2GQMaUg+3r7ucrx82kpqotjv0xHghNIm95aBr1Qw" + - "1gaEjsC/0wGmmBDg1dTDH+F1p9TInzr3EFuYD0YiQ7YlAHq3cPuyGoLXJ5dXYuSBfhDXJSeddUkl" + - "k1ufZyOOcskeInQge7jzaRfmKg3U94r+spMEvb0AzDQVOKvjjo1ivxMSgFRZaDb/4qw="; - - /** - * Defines the keystore contents for the server, JKS version. Holds just a - * single self-generated key. The subject name is "Test Server". - */ - private static final String SERVER_KEYS_JKS = - "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFfBeAAAArowggK2MA4GCisGAQQBKgIRAQEFAASC" + - "AqI2kp5XjnF8YZkhcF92YsJNQkvsmH7zqMM87j23zSoV4DwyE3XeC/gZWq1ToScIhoqZkzlbWcu4" + - "T/Zfc/DrfGk/rKbBL1uWKGZ8fMtlZk8KoAhxZk1JSyJvdkyKxqmzUbxk1OFMlN2VJNu97FPVH+du" + - "dvjTvmpdoM81INWBW/1fZJeQeDvn4mMbbe0IxgpiLnI9WSevlaDP/sm1X3iO9yEyzHLL+M5Erspo" + - "Cwa558fOu5DdsICMXhvDQxjWFKFhPHnKtGe+VvwkG9/bAaDgx3kfhk0w5zvdnkKb+8Ed9ylNRzdk" + - "ocAa/mxlMTOsTvDKXjjsBupNPIIj7OP4GNnZaxkJjSs98pEO67op1GX2qhy6FSOPNuq8k/65HzUc" + - "PYn6voEeh6vm02U/sjEnzRevQ2+2wXoAdp0EwtQ/DlMe+NvcwPGWKuMgX4A4L93DZGb04N2VmAU3" + - "YLOtZwTO0LbuWrcCM/q99G/7LcczkxIVrO2I/rh8RXVczlf9QzcrFObFv4ATuspWJ8xG7DhsMbnk" + - "rT94Pq6TogYeoz8o8ZMykesAqN6mt/9+ToIemmXv+e+KU1hI5oLwWMnUG6dXM6hIvrULY6o+QCPH" + - "172YQJMa+68HAeS+itBTAF4Clm/bLn6reHCGGU6vNdwU0lYldpiOj9cB3t+u2UuLo6tiFWjLf5Zs" + - "EQJETd4g/EK9nHxJn0GAKrWnTw7pEHQJ08elzUuy04C/jEEG+4QXU1InzS4o/kR0Sqz2WTGDoSoq" + - "ewuPRU5bzQs/b9daq3mXrnPtRBL6HfSDAdpTK76iHqLCGdqx3avHjVSBm4zFvEuYBCev+3iKOBmg" + - "yh7eQRTjz4UOWfy85omMBr7lK8PtfVBDzOXpasxS0uBgdUyBDX4tO6k9jZ8a1kmQRQAAAAEABVgu" + - "NTA5AAACSDCCAkQwggGtAgRIR8SKMA0GCSqGSIb3DQEBBAUAMGkxCzAJBgNVBAYTAlVTMRMwEQYD" + - "VQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzANBgNVBAoTBkdvb2dsZTEQMA4GA1UECxMH" + - "QW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBTZXJ2ZXIwHhcNMDgwNjA1MTA0ODQyWhcNMDgwOTAzMTA0" + - "ODQyWjBpMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8w" + - "DQYDVQQKEwZHb29nbGUxEDAOBgNVBAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMIGf" + - "MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwoC6chqCI84rj1PrXuJgbiit4EV909zR6N0jNlYfg" + - "itwB39bP39wH03rFm8T59b3mbSptnGmCIpLZn25KPPFsYD3JJ+wFlmiUdEP9H05flfwtFQJnw9uT" + - "3rRIdYVMPcQ3RoZzwAMliGr882I2thIDbA6xjGU/1nRIdvk0LtxH3QIDAQABMA0GCSqGSIb3DQEB" + - "BAUAA4GBAJn+6YgUlY18Ie+0+Vt8oEi81DNi/bfPrAUAh63fhhBikx/3R9dl3wh09Z6p7cIdNxjW" + - "n2ll+cRW9eqF7z75F0Omm0C7/KAEPjukVbszmzeU5VqzkpSt0j84YWi+TfcHRrfvhLbrlmGITVpY" + - "ol5pHLDyqGmDs53pgwipWqsn/nEXEBgj3EoqPeqHbDf7YaP8h/5BSt0="; - - private String PASSWORD = "android"; - - /** - * Loads a keystore from a base64-encoded String. Returns the KeyManager[] - * for the result. - */ - private KeyManager[] getKeyManagers() throws Exception { - String keys = (useBKS ? SERVER_KEYS_BKS : SERVER_KEYS_JKS); - byte[] bytes = Base64.decode(keys.getBytes()); - InputStream inputStream = new ByteArrayInputStream(bytes); - - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(inputStream, PASSWORD.toCharArray()); - inputStream.close(); - - String algorithm = KeyManagerFactory.getDefaultAlgorithm(); - KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm); - keyManagerFactory.init(keyStore, PASSWORD.toCharArray()); - - return keyManagerFactory.getKeyManagers(); - } - - private SSLServerSocket getSSLServerSocket() throws Exception { - SSLContext context = SSLContext.getInstance("TLS"); - context.init(getKeyManagers(), null, null); - SSLServerSocket sss = (SSLServerSocket) context.getServerSocketFactory() - .createServerSocket(); - return sss; - } - - public void test_creationStressTest() throws Exception { - KeyManager[] keyManagers = getKeyManagers(); - // Test the default codepath, which uses /dev/urandom. - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyManagers, null, null); - for (int i = 0; i < 2048; ++i) { - sslContext.getServerSocketFactory().createServerSocket().close(); - } - - // Test the other codepath, which copies a seed from a byte[]. - sslContext.init(keyManagers, null, new SecureRandom()); - for (int i = 0; i < 2048; ++i) { - sslContext.getServerSocketFactory().createServerSocket().close(); - } - } -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionBindingEventTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionBindingEventTest.java deleted file mode 100644 index dfccf68..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionBindingEventTest.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.net.ssl; - -import java.security.Principal; -import java.security.cert.Certificate; - -import javax.net.ssl.SSLPeerUnverifiedException; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSessionContext; -import javax.net.ssl.SSLSessionBindingEvent; -import javax.security.cert.X509Certificate; - -import junit.framework.TestCase; - -/** - * Tests for <code>SSLSessionBindingEvent</code> class constructors and methods. - * - */ -public class SSLSessionBindingEventTest extends TestCase { - - public final void test_ConstructorLjavax_net_ssl_SSLSessionLjava_lang_String() { - SSLSession ses = new MySSLSession(); - - try { - SSLSessionBindingEvent event = new SSLSessionBindingEvent(ses, "test"); - if (!"test".equals(event.getName())) { - fail("incorrect name"); - } - if (!event.getSession().equals(ses)) { - fail("incorrect session"); - } - } catch (Exception e) { - fail("Unexpected exception " + e); - } - - try { - SSLSessionBindingEvent event = new SSLSessionBindingEvent(null, "test"); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - // expected - } - - try { - SSLSessionBindingEvent event = new SSLSessionBindingEvent(ses, null); - } catch (IllegalArgumentException e) { - fail("Unexpected IllegalArgumentException: " + e); - } - } - - /** - * javax.net.ssl.SSLSessionBindingEvent#getName() - */ - public void test_getName() { - SSLSession ses = new MySSLSession(); - SSLSessionBindingEvent event = new SSLSessionBindingEvent(ses, "test"); - assertEquals("Incorrect session name", "test", event.getName()); - event = new SSLSessionBindingEvent(ses, null); - assertEquals("Incorrect session name", null, event.getName()); - } - - /** - * javax.net.ssl.SSLSessionBindingEvent#getSession() - */ - public void test_getSession() { - SSLSession ses = new MySSLSession(); - SSLSessionBindingEvent event = new SSLSessionBindingEvent(ses, "test"); - assertEquals("Incorrect session", ses, event.getSession()); - } -} - -class MySSLSession implements SSLSession { - /* - * @see javax.net.ssl.SSLSession#getApplicationBufferSize() - */ - public int getApplicationBufferSize() { - return 0; - } - - /* - * @see javax.net.ssl.SSLSession#getCipherSuite() - */ - public String getCipherSuite() { - return "MyTestCipherSuite"; - } - - /* - * @see javax.net.ssl.SSLSession#getCreationTime() - */ - public long getCreationTime() { - return 0; - } - - /* - * @see javax.net.ssl.SSLSession#getId() - */ - public byte[] getId() { - return null; - } - - /* - * @see javax.net.ssl.SSLSession#getLastAccessedTime() - */ - public long getLastAccessedTime() { - return 0; - } - - /* - * @see javax.net.ssl.SSLSession#getLocalCertificates() - */ - public Certificate[] getLocalCertificates() { - return null; - } - - /* - * @see javax.net.ssl.SSLSession#getLocalPrincipal() - */ - public Principal getLocalPrincipal() { - return null; - } - - /* - * @see javax.net.ssl.SSLSession#getPacketBufferSize() - */ - public int getPacketBufferSize() { - return 0; - } - - /* - * @see javax.net.ssl.SSLSession#getPeerCertificateChain() - */ - public X509Certificate[] getPeerCertificateChain() - throws SSLPeerUnverifiedException { - throw new SSLPeerUnverifiedException("test exception"); - } - - /* - * @see javax.net.ssl.SSLSession#getPeerCertificates() - */ - public Certificate[] getPeerCertificates() - throws SSLPeerUnverifiedException { - throw new SSLPeerUnverifiedException("test exception"); - } - - /* - * @see javax.net.ssl.SSLSession#getPeerHost() - */ - public String getPeerHost() { - return null; - } - - /* - * @see javax.net.ssl.SSLSession#getPeerPort() - */ - public int getPeerPort() { - return 0; - } - - /* - * @see javax.net.ssl.SSLSession#getPeerPrincipal() - */ - public Principal getPeerPrincipal() throws SSLPeerUnverifiedException { - return null; - } - - /* - * @see javax.net.ssl.SSLSession#getProtocol() - */ - public String getProtocol() { - return null; - } - - /* - * @see javax.net.ssl.SSLSession#getSessionContext() - */ - public SSLSessionContext getSessionContext() { - return null; - } - - /* - * @see javax.net.ssl.SSLSession#getValue(java.lang.String) - */ - public Object getValue(String name) { - return null; - } - - /* - * @see javax.net.ssl.SSLSession#getValueNames() - */ - public String[] getValueNames() { - return null; - } - - /* - * @see javax.net.ssl.SSLSession#invalidate() - */ - public void invalidate() { - } - - /* - * @see javax.net.ssl.SSLSession#isValid() - */ - public boolean isValid() { - return false; - } - - /* - * @see javax.net.ssl.SSLSession#putValue(java.lang.String, - * java.lang.Object) - */ - public void putValue(String name, Object value) { - } - - /* - * @see javax.net.ssl.SSLSession#removeValue(java.lang.String) - */ - public void removeValue(String name) { - } - -} - diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionBindingListenerTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionBindingListenerTest.java deleted file mode 100644 index a006a83..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionBindingListenerTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.net.ssl; - -import javax.net.ssl.SSLServerSocket; -import javax.net.ssl.SSLServerSocketFactory; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSessionBindingEvent; -import javax.net.ssl.SSLSessionBindingListener; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.SSLSocketFactory; - -import java.io.IOException; -import java.net.UnknownHostException; - -import junit.framework.TestCase; - -/** - * Tests for SSLSessionBindingListener class - * - */ -public class SSLSessionBindingListenerTest extends TestCase { - - public class mySSLSessionBindingListener implements SSLSessionBindingListener { - - public boolean boundDone = false; - public boolean unboundDone = false; - - mySSLSessionBindingListener() { - } - - public void valueBound(SSLSessionBindingEvent event) { - if (event != null) boundDone = true; - } - public void valueUnbound(SSLSessionBindingEvent event) { - if (event != null) unboundDone = true; - } - } - - /** - * @throws IOException - * @throws UnknownHostException - * @throws InterruptedException - * javax.net.ssl.SSLSessionBindingListener#valueBound(SSLSessionBindingEvent event) - */ - public void test_valueBound() throws UnknownHostException, IOException, - InterruptedException { - SSLSocket sock = (SSLSocket) SSLSocketFactory.getDefault() - .createSocket(); - SSLSession ss = sock.getSession(); - mySSLSessionBindingListener sbl = new mySSLSessionBindingListener(); - ss.putValue("test", sbl); - assertTrue("valueBound was not called.", sbl.boundDone); - } - - /** - * @throws IOException - * @throws UnknownHostException - * javax.net.ssl.SSLSessionBindingListener#valueUnbound(SSLSessionBindingEvent event) - */ - public void test_valueUnbound() throws UnknownHostException, IOException { - SSLSocket sock = (SSLSocket) SSLSocketFactory.getDefault() - .createSocket(); - SSLSession ss = sock.getSession(); - mySSLSessionBindingListener sbl = new mySSLSessionBindingListener(); - ss.putValue("test", sbl); - ss.removeValue("test"); - assertTrue("valueUnbound was not called.", sbl.unboundDone); - } -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionContextTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionContextTest.java deleted file mode 100644 index aa95eb8..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionContextTest.java +++ /dev/null @@ -1,95 +0,0 @@ -package tests.api.javax.net.ssl; - -import junit.framework.TestCase; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSessionContext; - -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; - -/** - * Tests for <code>SSLSessionContext</code> class constructors and methods. - */ -public class SSLSessionContextTest extends TestCase { - - /** - * @throws NoSuchAlgorithmException - * @throws KeyManagementException - * javax.net.ssl.SSLSessionContex#getSessionCacheSize() - * javax.net.ssl.SSLSessionContex#setSessionCacheSize(int size) - */ - public final void test_sessionCacheSize() throws NoSuchAlgorithmException, KeyManagementException { - SSLContext context = SSLContext.getInstance("TLS"); - context.init(null, null, null); - SSLSessionContext sc = context - .getClientSessionContext(); - sc.setSessionCacheSize(10); - assertEquals("10 wasn't returned", 10, sc.getSessionCacheSize()); - sc.setSessionCacheSize(5); - assertEquals("5 wasn't returned", 5, sc.getSessionCacheSize()); - - try { - sc.setSessionCacheSize(-1); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iae) { - //expected - } - } - - /** - * @throws NoSuchAlgorithmException - * @throws KeyManagementException - * javax.net.ssl.SSLSessionContex#getSessionTimeout() - * javax.net.ssl.SSLSessionContex#setSessionTimeout(int seconds) - */ - public final void test_sessionTimeout() throws NoSuchAlgorithmException, KeyManagementException { - SSLContext context = SSLContext.getInstance("TLS"); - context.init(null, null, null); - SSLSessionContext sc = context - .getClientSessionContext(); - sc.setSessionTimeout(100); - assertEquals("100 wasn't returned", 100, sc.getSessionTimeout()); - sc.setSessionTimeout(5000); - assertEquals("5000 wasn't returned", 5000, sc.getSessionTimeout()); - - try { - sc.setSessionTimeout(-1); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iae) { - //expected - } - } - - /** - * @throws NoSuchAlgorithmException - * @throws KeyManagementException - * javax.net.ssl.SSLSessionContex#getSession(byte[] sessionId) - */ - public final void test_getSession() throws NoSuchAlgorithmException, KeyManagementException { - SSLContext context = SSLContext.getInstance("TLS"); - context.init(null, null, null); - SSLSessionContext sc = context - .getClientSessionContext(); - try { - sc.getSession(null); - } catch (NullPointerException e) { - // expected - } - assertNull(sc.getSession(new byte[5])); - } - - /** - * @throws NoSuchAlgorithmException - * @throws KeyManagementException - * javax.net.ssl.SSLSessionContex#getIds() - */ - public final void test_getIds() throws NoSuchAlgorithmException, KeyManagementException { - SSLContext context = SSLContext.getInstance("TLS"); - context.init(null, null, null); - SSLSessionContext sc = context - .getClientSessionContext(); - assertFalse(sc.getIds().hasMoreElements()); - } - -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionTest.java deleted file mode 100644 index 5084422..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionTest.java +++ /dev/null @@ -1,641 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.net.ssl; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.security.KeyStore; -import java.security.Principal; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import javax.net.ssl.KeyManager; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLServerSocket; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSessionBindingEvent; -import javax.net.ssl.SSLSessionBindingListener; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.TrustManager; -import junit.framework.TestCase; -import libcore.io.Base64; -import tests.api.javax.net.ssl.HandshakeCompletedEventTest.MyHandshakeListener; -import tests.api.javax.net.ssl.HandshakeCompletedEventTest.TestTrustManager; - -public class SSLSessionTest extends TestCase { - - // set to true if on Android, false if on RI - boolean useBKS = true; - - /** - * javax.net.ssl.SSLSession#getPeerHost() - * javax.net.ssl.SSLSession#getPeerPort() - */ - public void test_getPeerHost() throws Exception { - SSLSession s = clientSession; - assertEquals(InetAddress.getLocalHost().getHostName(), s.getPeerHost()); - assertEquals(serverSocket.getLocalPort(), s.getPeerPort()); - } - - /** - * javax.net.ssl.SSLSession#invalidate() - * javax.net.ssl.SSLSession#isValid() - */ - public void test_invalidate() { - SSLSession s = clientSession; - assertTrue(s.isValid()); - s.invalidate(); - assertFalse(s.isValid()); - } - - /** - * javax.net.ssl.SSLSession#getPeerPrincipal() - */ - public void test_getPeerPrincipal() throws Exception { - Principal p1 = clientSession.getPeerPrincipal(); - KeyStore store = server.getStore(); - X509Certificate cert = (X509Certificate)store.getCertificate("mykey"); - Principal p2 = cert.getSubjectX500Principal(); - assertEquals(p1, p2); - } - - /** - * javax.net.ssl.SSLSession#getApplicationBufferSize() - */ - public void test_getApplicationBufferSize() { - assertTrue(clientSession.getApplicationBufferSize() > 0); - } - - /** - * javax.net.ssl.SSLSession#getCipherSuite() - */ - public void test_getCipherSuite() { - assertEquals(CIPHER_SUITE, clientSession.getCipherSuite()); - } - - /** - * javax.net.ssl.SSLSession#getCreationTime() - */ - public void test_getCreationTime() { - // check if creation time was in the last 10 seconds - long currentTime = System.currentTimeMillis(); - long sessionTime = clientSession.getCreationTime(); - long diff = currentTime - sessionTime; - assertTrue("diff between " + currentTime + " and " + sessionTime + " should be < 10000", - diff < 10000); - } - - /** - * javax.net.ssl.SSLSession#getId() - */ - public void test_getId() { - byte[] id = clientSession.getId(); - SSLSession sess = clientSslContext.getClientSessionContext().getSession(id); - assertNotNull("Could not find session for id " + id, sess); - assertEquals(clientSession, sess); - } - - /** - * javax.net.ssl.SSLSession#getLastAccessedTime() - */ - public void test_getLastAccessedTime() { - // check if last access time was in the last 10 seconds - long currentTime = System.currentTimeMillis(); - long sessionTime = clientSession.getLastAccessedTime(); - long diff = currentTime - sessionTime; - assertTrue("diff between " + currentTime + " and " + sessionTime + " should be < 10000", - diff < 10000); - assertTrue ("diff should be < 10000 but is " + diff, diff < 10000); - } - - /** - * javax.net.ssl.SSLSession#getLocalCertificates() - */ - public void test_getLocalCertificates() throws Exception { - KeyStore store = client.getStore(); - Certificate cert = store.getCertificate("mykey"); - Certificate[] certs = clientSession.getLocalCertificates(); - assertEquals(cert, certs[0]); - } - - /** - * javax.net.ssl.SSLSession#getLocalPrincipal() - */ - public void test_getLocalPrincipal() throws Exception { - Principal p1 = clientSession.getLocalPrincipal(); - KeyStore store = client.getStore(); - X509Certificate cert = (X509Certificate)store.getCertificate("mykey"); - Principal p2 = cert.getSubjectX500Principal(); - assertEquals(p1, p2); - } - - /** - * javax.net.ssl.SSLSession#getPacketBufferSize() - */ - public void test_getPacketBufferSize() { - assertTrue(clientSession.getPacketBufferSize() > 0); - } - - /** - * javax.net.ssl.SSLSession#getPeerCertificates() - */ - public void test_getPeerCertificates() throws Exception { - Certificate[] res = clientSession.getPeerCertificates(); - assertTrue(res.length > 0); - } - - /** - * javax.net.ssl.SSLSession#getPeerCertificateChain() - */ - public void test_getPeerCertificateChain() throws Exception { - javax.security.cert.X509Certificate[] res = clientSession.getPeerCertificateChain(); - assertTrue(res.length > 0); - } - - /** - * javax.net.ssl.SSLSession#getProtocol() - */ - public void test_getProtocol() { - assertEquals("TLSv1", clientSession.getProtocol()); - } - - /** - * javax.net.ssl.SSLSession#getSessionContext() - */ - public void test_getSessionContext() { - assertEquals(clientSession.getSessionContext(), - clientSslContext.getClientSessionContext()); - } - - /** - * javax.net.ssl.SSLSession#putValue(String name, Object value) - * javax.net.ssl.SSLSession#removeValue(String name) - * javax.net.ssl.SSLSession#getValueNames() - */ - public void test_putValue() { - SSLSession s = clientSession; - mySSLSessionBindingListener sbl = new mySSLSessionBindingListener(); - assertNotNull(s.getValueNames()); - assertEquals(0, s.getValueNames().length); - s.putValue("Name_01", sbl); - s.putValue("Name_02", sbl); - s.putValue("Name_03", sbl); - assertEquals(3, s.getValueNames().length); - s.removeValue("Name_01"); - assertEquals(2, s.getValueNames().length); - - try { - s.putValue(null, null); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException expected) { - // expected - } - try { - s.putValue("ABC", null); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException expected) { - // expected - } - try { - s.putValue(null, sbl); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException expected) { - // expected - } - - try { - s.removeValue(null); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException expected) { - // expected - } - } - - /** - * javax.net.ssl.SSLSession#getValue(String name) - */ - public void test_getValue() { - SSLSession s = clientSession; - mySSLSessionBindingListener sbl = new mySSLSessionBindingListener(); - - try { - s.getValue(null); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException expected) { - // expected - } - - s.putValue("Name", sbl); - Object obj = s.getValue("Name"); - assertTrue(obj instanceof SSLSessionBindingListener); - } - - Thread serverThread, clientThread; - TestServer server; - TestClient client; - - @Override - protected void setUp() throws Exception { - String serverKeys = (useBKS ? SERVER_KEYS_BKS : SERVER_KEYS_JKS); - String clientKeys = (useBKS ? CLIENT_KEYS_BKS : CLIENT_KEYS_JKS); - server = new TestServer(true, TestServer.CLIENT_AUTH_WANTED, serverKeys); - client = new TestClient(true, clientKeys); - - serverThread = new Thread(server); - clientThread = new Thread(client); - - serverThread.start(); - try { - Thread.currentThread().sleep(1000); - clientThread.start(); - } catch (InterruptedException e) { - fail("Could not create server or cient " + e.getMessage()); - } - while (clientSession == null - && server.exception == null - && client.exception == null) { - try { - Thread.currentThread().sleep(500); - } catch (InterruptedException e) { - fail("couldn't create session"); - } - } - if (server.exception != null) { - server.exception.printStackTrace(); - } - assertNull("server thread has a pending exception: " + server.exception, - server.exception); - if (client.exception != null) { - client.exception.printStackTrace(); - } - assertNull("client thread has a pending exception: " + client.exception, - client.exception); - assertNotNull("Could not initialize session", clientSession); - } - - @Override - protected void tearDown() { - notFinished = false; - try { - serverThread.join(); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - try { - clientThread.join(); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - - // The server must have completed without an exception. - if (server.getException() != null) { - throw new RuntimeException(server.getException()); - } - - // The client must have completed without an exception. - if (client.getException() != null) { - throw new RuntimeException(client.getException()); - } - } - - public class mySSLSessionBindingListener implements - SSLSessionBindingListener { - mySSLSessionBindingListener() { - } - public void valueBound(SSLSessionBindingEvent event) {} - public void valueUnbound(SSLSessionBindingEvent event) {} - } - - /** - * Defines the keystore contents for the server, BKS version. Holds just a - * single self-generated key. The subject name is "Test Server". - */ - private static final String SERVER_KEYS_BKS = - "AAAAAQAAABQDkebzoP1XwqyWKRCJEpn/t8dqIQAABDkEAAVteWtleQAAARpYl20nAAAAAQAFWC41" - + "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU1jANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET" - + "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV" - + "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMB4XDTA4MDYwNTExNTgxNFoXDTA4MDkw" - + "MzExNTgxNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U" - + "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IFNlcnZl" - + "cjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0LIdKaIr9/vsTq8BZlA3R+NFWRaH4lGsTAQy" - + "DPMF9ZqEDOaL6DJuu0colSBBBQ85hQTPa9m9nyJoN3pEi1hgamqOvQIWcXBk+SOpUGRZZFXwniJV" - + "zDKU5nE9MYgn2B9AoiH3CSuMz6HRqgVaqtppIe1jhukMc/kHVJvlKRNy9XMCAwEAATANBgkqhkiG" - + "9w0BAQUFAAOBgQC7yBmJ9O/eWDGtSH9BH0R3dh2NdST3W9hNZ8hIa8U8klhNHbUCSSktZmZkvbPU" - + "hse5LI3dh6RyNDuqDrbYwcqzKbFJaq/jX9kCoeb3vgbQElMRX8D2ID1vRjxwlALFISrtaN4VpWzV" - + "yeoHPW4xldeZmoVtjn8zXNzQhLuBqX2MmAAAAqwAAAAUvkUScfw9yCSmALruURNmtBai7kQAAAZx" - + "4Jmijxs/l8EBaleaUru6EOPioWkUAEVWCxjM/TxbGHOi2VMsQWqRr/DZ3wsDmtQgw3QTrUK666sR" - + "MBnbqdnyCyvM1J2V1xxLXPUeRBmR2CXorYGF9Dye7NkgVdfA+9g9L/0Au6Ugn+2Cj5leoIgkgApN" - + "vuEcZegFlNOUPVEs3SlBgUF1BY6OBM0UBHTPwGGxFBBcetcuMRbUnu65vyDG0pslT59qpaR0TMVs" - + "P+tcheEzhyjbfM32/vwhnL9dBEgM8qMt0sqF6itNOQU/F4WGkK2Cm2v4CYEyKYw325fEhzTXosck" - + "MhbqmcyLab8EPceWF3dweoUT76+jEZx8lV2dapR+CmczQI43tV9btsd1xiBbBHAKvymm9Ep9bPzM" - + "J0MQi+OtURL9Lxke/70/MRueqbPeUlOaGvANTmXQD2OnW7PISwJ9lpeLfTG0LcqkoqkbtLKQLYHI" - + "rQfV5j0j+wmvmpMxzjN3uvNajLa4zQ8l0Eok9SFaRr2RL0gN8Q2JegfOL4pUiHPsh64WWya2NB7f" - + "V+1s65eA5ospXYsShRjo046QhGTmymwXXzdzuxu8IlnTEont6P4+J+GsWk6cldGbl20hctuUKzyx" - + "OptjEPOKejV60iDCYGmHbCWAzQ8h5MILV82IclzNViZmzAapeeCnexhpXhWTs+xDEYSKEiG/camt" - + "bhmZc3BcyVJrW23PktSfpBQ6D8ZxoMfF0L7V2GQMaUg+3r7ucrx82kpqotjv0xHghNIm95aBr1Qw" - + "1gaEjsC/0wGmmBDg1dTDH+F1p9TInzr3EFuYD0YiQ7YlAHq3cPuyGoLXJ5dXYuSBfhDXJSeddUkl" - + "k1ufZyOOcskeInQge7jzaRfmKg3U94r+spMEvb0AzDQVOKvjjo1ivxMSgFRZaDb/4qw="; - - /** - * Defines the keystore contents for the client, BKS version. Holds just a - * single self-generated key. The subject name is "Test Client". - */ - private static final String CLIENT_KEYS_BKS = - "AAAAAQAAABT4Rka6fxbFps98Y5k2VilmbibNkQAABfQEAAVteWtleQAAARpYl+POAAAAAQAFWC41" - + "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU9TANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET" - + "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV" - + "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgQ2xpZW50MB4XDTA4MDYwNTExNTg0NVoXDTA4MDkw" - + "MzExNTg0NVowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U" - + "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IENsaWVu" - + "dDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEApUvmWsQDHPpbDKK13Yez2/q54tTOmRml/qva" - + "2K6dZjkjSTW0iRuk7ztaVEvdJpfVIDv1oBsCI51ttyLHROy1epjF+GoL74mJb7fkcd0VOoSOTjtD" - + "+3GgZkHPAm5YmUYxiJXqxKKJJqMCTIW46eJaA2nAep9QIwZ14/NFAs4ObV8CAwEAATANBgkqhkiG" - + "9w0BAQUFAAOBgQCJrCr3hZQFDlLIfsSKI1/w+BLvyf4fubOid0pBxfklR8KBNPTiqjSmu7pd/C/F" - + "1FR8CdZUDoPflZHCOU+fj5r5KUC1HyigY/tEUvlforBpfB0uCF+tXW4DbUfOWhfMtLV4nCOJOOZg" - + "awfZLJWBJouLKOp427vDftxTSB+Ks8YjlgAAAqwAAAAU+NH6TtrzjyDdCXm5B6Vo7xX5G4YAAAZx" - + "EAUkcZtmykn7YdaYxC1jRFJ+GEJpC8nZVg83QClVuCSIS8a5f8Hl44Bk4oepOZsPzhtz3RdVzDVi" - + "RFfoyZFsrk9F5bDTVJ6sQbb/1nfJkLhZFXokka0vND5AXMSoD5Bj1Fqem3cK7fSUyqKvFoRKC3XD" - + "FQvhqoam29F1rbl8FaYdPvhhZo8TfZQYUyUKwW+RbR44M5iHPx+ykieMe/C/4bcM3z8cwIbYI1aO" - + "gjQKS2MK9bs17xaDzeAh4sBKrskFGrDe+2dgvrSKdoakJhLTNTBSG6m+rzqMSCeQpafLKMSjTSSz" - + "+KoQ9bLyax8cbvViGGju0SlVhquloZmKOfHr8TukIoV64h3uCGFOVFtQjCYDOq6NbfRvMh14UVF5" - + "zgDIGczoD9dMoULWxBmniGSntoNgZM+QP6Id7DBasZGKfrHIAw3lHBqcvB5smemSu7F4itRoa3D8" - + "N7hhUEKAc+xA+8NKmXfiCBoHfPHTwDvt4IR7gWjeP3Xv5vitcKQ/MAfO5RwfzkYCXQ3FfjfzmsE1" - + "1IfLRDiBj+lhQSulhRVStKI88Che3M4JUNGKllrc0nt1pWa1vgzmUhhC4LSdm6trTHgyJnB6OcS9" - + "t2furYjK88j1AuB4921oxMxRm8c4Crq8Pyuf+n3YKi8Pl2BzBtw++0gj0ODlgwut8SrVj66/nvIB" - + "jN3kLVahR8nZrEFF6vTTmyXi761pzq9yOVqI57wJGx8o3Ygox1p+pWUPl1hQR7rrhUbgK/Q5wno9" - + "uJk07h3IZnNxE+/IKgeMTP/H4+jmyT4mhsexJ2BFHeiKF1KT/FMcJdSi+ZK5yoNVcYuY8aZbx0Ef" - + "lHorCXAmLFB0W6Cz4KPP01nD9YBB4olxiK1t7m0AU9zscdivNiuUaB5OIEr+JuZ6dNw="; - - private static final String CIPHER_SUITE = "SSL_RSA_WITH_RC4_128_MD5"; - /** - * Defines the keystore contents for the server, JKS version. Holds just a - * single self-generated key. The subject name is "Test Server". - */ - private static final String SERVER_KEYS_JKS = - "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFfBeAAAArowggK2MA4GCisGAQQBKgIRAQEFAASC" - + "AqI2kp5XjnF8YZkhcF92YsJNQkvsmH7zqMM87j23zSoV4DwyE3XeC/gZWq1ToScIhoqZkzlbWcu4" - + "T/Zfc/DrfGk/rKbBL1uWKGZ8fMtlZk8KoAhxZk1JSyJvdkyKxqmzUbxk1OFMlN2VJNu97FPVH+du" - + "dvjTvmpdoM81INWBW/1fZJeQeDvn4mMbbe0IxgpiLnI9WSevlaDP/sm1X3iO9yEyzHLL+M5Erspo" - + "Cwa558fOu5DdsICMXhvDQxjWFKFhPHnKtGe+VvwkG9/bAaDgx3kfhk0w5zvdnkKb+8Ed9ylNRzdk" - + "ocAa/mxlMTOsTvDKXjjsBupNPIIj7OP4GNnZaxkJjSs98pEO67op1GX2qhy6FSOPNuq8k/65HzUc" - + "PYn6voEeh6vm02U/sjEnzRevQ2+2wXoAdp0EwtQ/DlMe+NvcwPGWKuMgX4A4L93DZGb04N2VmAU3" - + "YLOtZwTO0LbuWrcCM/q99G/7LcczkxIVrO2I/rh8RXVczlf9QzcrFObFv4ATuspWJ8xG7DhsMbnk" - + "rT94Pq6TogYeoz8o8ZMykesAqN6mt/9+ToIemmXv+e+KU1hI5oLwWMnUG6dXM6hIvrULY6o+QCPH" - + "172YQJMa+68HAeS+itBTAF4Clm/bLn6reHCGGU6vNdwU0lYldpiOj9cB3t+u2UuLo6tiFWjLf5Zs" - + "EQJETd4g/EK9nHxJn0GAKrWnTw7pEHQJ08elzUuy04C/jEEG+4QXU1InzS4o/kR0Sqz2WTGDoSoq" - + "ewuPRU5bzQs/b9daq3mXrnPtRBL6HfSDAdpTK76iHqLCGdqx3avHjVSBm4zFvEuYBCev+3iKOBmg" - + "yh7eQRTjz4UOWfy85omMBr7lK8PtfVBDzOXpasxS0uBgdUyBDX4tO6k9jZ8a1kmQRQAAAAEABVgu" - + "NTA5AAACSDCCAkQwggGtAgRIR8SKMA0GCSqGSIb3DQEBBAUAMGkxCzAJBgNVBAYTAlVTMRMwEQYD" - + "VQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzANBgNVBAoTBkdvb2dsZTEQMA4GA1UECxMH" - + "QW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBTZXJ2ZXIwHhcNMDgwNjA1MTA0ODQyWhcNMDgwOTAzMTA0" - + "ODQyWjBpMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8w" - + "DQYDVQQKEwZHb29nbGUxEDAOBgNVBAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMIGf" - + "MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwoC6chqCI84rj1PrXuJgbiit4EV909zR6N0jNlYfg" - + "itwB39bP39wH03rFm8T59b3mbSptnGmCIpLZn25KPPFsYD3JJ+wFlmiUdEP9H05flfwtFQJnw9uT" - + "3rRIdYVMPcQ3RoZzwAMliGr882I2thIDbA6xjGU/1nRIdvk0LtxH3QIDAQABMA0GCSqGSIb3DQEB" - + "BAUAA4GBAJn+6YgUlY18Ie+0+Vt8oEi81DNi/bfPrAUAh63fhhBikx/3R9dl3wh09Z6p7cIdNxjW" - + "n2ll+cRW9eqF7z75F0Omm0C7/KAEPjukVbszmzeU5VqzkpSt0j84YWi+TfcHRrfvhLbrlmGITVpY" - + "ol5pHLDyqGmDs53pgwipWqsn/nEXEBgj3EoqPeqHbDf7YaP8h/5BSt0="; - - /** - * Defines the keystore contents for the client, JKS version. Holds just a - * single self-generated key. The subject name is "Test Client". - */ - private static final String CLIENT_KEYS_JKS = - "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFhyMAAAArkwggK1MA4GCisGAQQBKgIRAQEFAASC" - + "AqGVSfXolBStZy4nnRNn4fAr+S7kfU2BS23wwW8uB2Ru3GvtLzlK9q08Gvq/LNqBafjyFTVL5FV5" - + "SED/8YomO5a98GpskSeRvytCiTBLJdgGhws5TOGekgIAcBROPGIyOtJPQ0HfOQs+BqgzGDHzHQhw" - + "u/8Tm6yQwiP+W/1I9B1QnaEztZA3mhTyMMJsmsFTYroGgAog885D5Cmzd8sYGfxec3R6I+xcmBAY" - + "eibR5kGpWwt1R+qMvRrtBqh5r6WSKhCBNax+SJVbtUNRiKyjKccdJg6fGqIWWeivwYTy0OhjA6b4" - + "NiZ/ZZs5pxFGWUj/Rlp0RYy8fCF6aw5/5s4Bf4MI6dPSqMG8Hf7sJR91GbcELyzPdM0h5lNavgit" - + "QPEzKeuDrGxhY1frJThBsNsS0gxeu+OgfJPEb/H4lpYX5IvuIGbWKcxoO9zq4/fimIZkdA8A+3eY" - + "mfDaowvy65NBVQPJSxaOyFhLHfeLqOeCsVENAea02vA7andZHTZehvcrqyKtm+z8ncHGRC2H9H8O" - + "jKwKHfxxrYY/jMAKLl00+PBb3kspO+BHI2EcQnQuMw/zr83OR9Meq4TJ0TMuNkApZELAeFckIBbS" - + "rBr8NNjAIfjuCTuKHhsTFWiHfk9ZIzigxXagfeDRiyVc6khOuF/bGorj23N2o7Rf3uLoU6PyXWi4" - + "uhctR1aL6NzxDoK2PbYCeA9hxbDv8emaVPIzlVwpPK3Ruvv9mkjcOhZ74J8bPK2fQmbplbOljcZi" - + "tZijOfzcO/11JrwhuJZRA6wanTqHoujgChV9EukVrmbWGGAcewFnAsSbFXIik7/+QznXaDIt5NgL" - + "H/Bcz4Z/fdV7Ae1eUaxKXdPbI//4J+8liVT/d8awjW2tldIaDlmGMR3aoc830+3mAAAAAQAFWC41" - + "MDkAAAJIMIICRDCCAa0CBEhHxLgwDQYJKoZIhvcNAQEEBQAwaTELMAkGA1UEBhMCVVMxEzARBgNV" - + "BAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01UVjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdB" - + "bmRyb2lkMRQwEgYDVQQDEwtUZXN0IENsaWVudDAeFw0wODA2MDUxMDQ5MjhaFw0wODA5MDMxMDQ5" - + "MjhaMGkxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzAN" - + "BgNVBAoTBkdvb2dsZTEQMA4GA1UECxMHQW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBDbGllbnQwgZ8w" - + "DQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAIK3Q+KiFbmCGg422TAo4gggdhMH6FJhiuz8DxRyeMKR" - + "UAfP4MK0wtc8N42waZ6OKvxpBFUy0BRfBsX0GD4Ku99yu9/tavSigTraeJtwV3WWRRjIqk7L3wX5" - + "cmgS2KSD43Y0rNUKrko26lnt9N4qiYRBSj+tcAN3Lx9+ptqk1LApAgMBAAEwDQYJKoZIhvcNAQEE" - + "BQADgYEANb7Q1GVSuy1RPJ0FmiXoMYCCtvlRLkmJphwxovK0cAQK12Vll+yAzBhHiQHy/RA11mng" - + "wYudC7u3P8X/tBT8GR1Yk7QW3KgFyPafp3lQBBCraSsfrjKj+dCLig1uBLUr4f68W8VFWZWWTHqp" - + "NMGpCX6qmjbkJQLVK/Yfo1ePaUexPSOX0G9m8+DoV3iyNw6at01NRw=="; - - - SSLServerSocket serverSocket; - MyHandshakeListener listener; - String host = "localhost"; - boolean notFinished = true; - SSLSession clientSession = null; - SSLContext clientSslContext = null; - String testData = "PING"; - - private String PASSWORD = "android"; - - /** - * Implements a test SSL socket server. It waits for a connection on a given - * port, requests client authentication (if specified), reads from the socket, - * and writes to the socket. - */ - class TestServer implements Runnable { - - public static final int CLIENT_AUTH_NONE = 0; - - public static final int CLIENT_AUTH_WANTED = 1; - - public static final int CLIENT_AUTH_NEEDED = 2; - - private TestTrustManager trustManager; - - private Exception exception; - - String keys; - - private int clientAuth; - - private boolean provideKeys; - - private KeyStore store; - - public TestServer(boolean provideKeys, int clientAuth, String keys) throws Exception { - this.keys = keys; - this.clientAuth = clientAuth; - this.provideKeys = provideKeys; - - trustManager = new TestTrustManager(); - - store = provideKeys ? getKeyStore(keys) : null; - KeyManager[] keyManagers = store != null ? getKeyManagers(store) : null; - TrustManager[] trustManagers = new TrustManager[] { trustManager }; - - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyManagers, trustManagers, null); - - serverSocket = (SSLServerSocket)sslContext.getServerSocketFactory().createServerSocket(); - - if (clientAuth == CLIENT_AUTH_WANTED) { - serverSocket.setWantClientAuth(true); - } else if (clientAuth == CLIENT_AUTH_NEEDED) { - serverSocket.setNeedClientAuth(true); - } else { - serverSocket.setWantClientAuth(false); - } - - serverSocket.bind(null); - } - - public void run() { - try { - SSLSocket clientSocket = (SSLSocket)serverSocket.accept(); - - InputStream istream = clientSocket.getInputStream(); - byte[] buffer = new byte[1024]; - istream.read(buffer); - - OutputStream ostream = clientSocket.getOutputStream(); - ostream.write(testData.getBytes()); - ostream.flush(); - - while (notFinished) { - Thread.currentThread().sleep(500); - } - - clientSocket.close(); - serverSocket.close(); - - } catch (Exception ex) { - exception = ex; - } - } - - public Exception getException() { - return exception; - } - - public javax.security.cert.X509Certificate[] getChain() { - return trustManager.getChain(); - } - - public KeyStore getStore() { - return store; - } - - } - - /** - * Implements a test SSL socket client. It opens a connection to localhost on - * a given port, writes to the socket, and reads from the socket. - */ - class TestClient implements Runnable { - - private TestTrustManager trustManager; - - private Exception exception; - - private String keys; - - private boolean provideKeys; - - private KeyStore store; - - public TestClient(boolean provideKeys, String keys) { - this.keys = keys; - this.provideKeys = provideKeys; - - trustManager = new TestTrustManager(); - } - - public void run() { - try { - store = provideKeys ? getKeyStore(keys) : null; - KeyManager[] keyManagers = store != null ? getKeyManagers(store) : null; - TrustManager[] trustManagers = new TrustManager[] { trustManager }; - - clientSslContext = SSLContext.getInstance("TLS"); - clientSslContext.init(keyManagers, trustManagers, null); - - SSLSocket socket = (SSLSocket)clientSslContext.getSocketFactory().createSocket(); - - socket.connect(serverSocket.getLocalSocketAddress()); - OutputStream ostream = socket.getOutputStream(); - ostream.write(testData.getBytes()); - ostream.flush(); - - InputStream istream = socket.getInputStream(); - byte[] buffer = new byte[1024]; - istream.read(buffer); - - clientSession = socket.getSession(); - while (notFinished) { - Thread.currentThread().sleep(500); - } - socket.close(); - - } catch (Exception ex) { - exception = ex; - } - } - - public Exception getException() { - return exception; - } - - public javax.security.cert.X509Certificate[] getChain() { - return trustManager.getChain(); - } - - public KeyStore getStore() { - return store; - } - } - - /** - * Loads a keystore from a base64-encoded String. Returns the KeyManager[] - * for the result. - */ - private KeyStore getKeyStore(String keys) throws Exception { - byte[] bytes = Base64.decode(keys.getBytes()); - InputStream inputStream = new ByteArrayInputStream(bytes); - - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(inputStream, PASSWORD.toCharArray()); - inputStream.close(); - return keyStore; - } - - /** - * Loads a keystore from a base64-encoded String. Returns the KeyManager[] - * for the result. - */ - private KeyManager[] getKeyManagers(KeyStore keyStore) throws Exception { - String algorithm = KeyManagerFactory.getDefaultAlgorithm(); - KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm); - keyManagerFactory.init(keyStore, PASSWORD.toCharArray()); - - return keyManagerFactory.getKeyManagers(); - } -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLSocketFactoryTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLSocketFactoryTest.java deleted file mode 100644 index 0d91116..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/SSLSocketFactoryTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.javax.net.ssl; - -import java.io.IOException; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.UnknownHostException; - -import javax.net.SocketFactory; -import javax.net.ssl.SSLSocketFactory; - -import junit.framework.TestCase; - -public class SSLSocketFactoryTest extends TestCase { - - private ServerSocket ss; - - protected int startServer(String name) { - try { - ss = new ServerSocket(0); - } catch (IOException e) { - fail(name + ": " + e); - } - return ss.getLocalPort(); - } - - /** - * javax.net.ssl.SSLSocketFactory#SSLSocketFactory() - */ - public void test_Constructor() { - try { - SocketFactory sf = SSLSocketFactory.getDefault(); - assertTrue(sf instanceof SSLSocketFactory); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - /** - * javax.net.ssl.SSLSocketFactory#getDefault() - */ - public void test_getDefault() { - assertNotNull("Incorrect default socket factory", - SSLSocketFactory.getDefault()); - } - - /** - * javax.net.ssl.SSLSocketFactory#createSocket(Socket s, String host, int port, boolean autoClose) - */ - public void test_createSocket() { - SSLSocketFactory sf = (SSLSocketFactory)SSLSocketFactory.getDefault(); - int sport = startServer("test_createSocket()"); - int[] invalid = { - Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE - }; - try { - Socket st = new Socket("localhost", sport); - Socket s = sf.createSocket(st, "localhost", sport, false); - assertFalse(s.isClosed()); - } catch (Exception ex) { - fail("Unexpected exception " + ex); - } - try { - Socket st = new Socket("localhost", sport); - Socket s = sf.createSocket(st, "localhost", sport, true); - s.close(); - assertTrue(st.isClosed()); - } catch (Exception ex) { - fail("Unexpected exception " + ex); - } - try { - sf.createSocket(null, "localhost", sport, true); - fail("IOException wasn't thrown"); - } catch (IOException ioe) { - // expected - } catch (NullPointerException e) { - // expected - } - for (int i = 0; i < invalid.length; i++) { - try { - Socket s = sf.createSocket(new Socket(), "localhost", 1080, false); - fail("IOException wasn't thrown"); - } catch (IOException ioe) { - // expected - } - } - - try { - Socket st = new Socket("bla-bla", sport); - Socket s = sf.createSocket(st, "bla-bla", sport, false); - fail("UnknownHostException wasn't thrown: " + "bla-bla"); - } catch (UnknownHostException uhe) { - // expected - } catch (Exception e) { - fail(e + " was thrown instead of UnknownHostException"); - } - } - - /** - * javax.net.ssl.SSLSocketFactory#getDefaultCipherSuites() - */ - public void test_getDefaultCipherSuites() { - try { - SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault(); - assertTrue("no default cipher suites returned", - sf.getDefaultCipherSuites().length > 0); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - /** - * javax.net.ssl.SSLSocketFactory#getSupportedCipherSuites() - */ - public void test_getSupportedCipherSuites() { - try { - SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault(); - assertTrue("no supported cipher suites returned", - sf.getSupportedCipherSuites().length > 0); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLSocketTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLSocketTest.java deleted file mode 100644 index b4cbde2..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/SSLSocketTest.java +++ /dev/null @@ -1,631 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.javax.net.ssl; - -import dalvik.annotation.AndroidOnly; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.UnknownHostException; -import java.security.KeyStore; -import java.security.SecureRandom; -import java.util.Arrays; -import javax.net.ssl.HandshakeCompletedEvent; -import javax.net.ssl.HandshakeCompletedListener; -import javax.net.ssl.KeyManager; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLServerSocket; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import javax.security.cert.X509Certificate; -import junit.framework.TestCase; -import libcore.io.Base64; -import tests.api.javax.net.ssl.HandshakeCompletedEventTest.TestTrustManager; -import libcore.java.security.StandardNames; - -public class SSLSocketTest extends TestCase { - - public class HandshakeCL implements HandshakeCompletedListener { - public void handshakeCompleted(HandshakeCompletedEvent event) { - } - } - - /** - * javax.net.ssl.SSLSocket#SSLSocket() - */ - public void testConstructor() throws Exception { - SSLSocket ssl = getSSLSocket(); - assertNotNull(ssl); - ssl.close(); - } - - /** - * javax.net.ssl.SSLSocket#SSLSocket(InetAddress address, int port) - */ - public void testConstructor_InetAddressI() throws Exception { - int sport = startServer("Cons InetAddress,I"); - int[] invalidPort = {-1, Integer.MIN_VALUE, 65536, Integer.MAX_VALUE}; - - SSLSocket ssl = getSSLSocket(InetAddress.getLocalHost(), sport); - assertNotNull(ssl); - assertEquals(sport, ssl.getPort()); - ssl.close(); - - try { - getSSLSocket(InetAddress.getLocalHost(), sport + 1); - fail(); - } catch (IOException expected) { - } - - for (int i = 0; i < invalidPort.length; i++) { - try { - getSSLSocket(InetAddress.getLocalHost(), invalidPort[i]); - fail(); - } catch (IllegalArgumentException expected) { - } - } - } - - /** - * javax.net.ssl.SSLSocket#SSLSocket(InetAddress address, int port, - * InetAddress clientAddress, int clientPort) - */ - public void testConstructor_InetAddressIInetAddressI() throws Exception { - int sport = startServer("Cons InetAddress,I,InetAddress,I"); - - SSLSocket ssl = getSSLSocket(InetAddress.getLocalHost(), sport, - InetAddress.getLocalHost(), 0); - assertNotNull(ssl); - assertEquals(sport, ssl.getPort()); - ssl.close(); - - try { - getSSLSocket(InetAddress.getLocalHost(), 8081, InetAddress.getLocalHost(), 8082); - fail(); - } catch (IOException expected) { - } - - try { - getSSLSocket(InetAddress.getLocalHost(), -1, InetAddress.getLocalHost(), sport + 1); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - getSSLSocket(InetAddress.getLocalHost(), sport, InetAddress.getLocalHost(), -1); - fail(); - } catch (IllegalArgumentException expected) { - } - - try { - getSSLSocket(InetAddress.getLocalHost(), Integer.MIN_VALUE, - InetAddress.getLocalHost(), sport + 1); - fail(); - } catch (IOException expectedOnRI) { - assertTrue(StandardNames.IS_RI); - } catch (IllegalArgumentException expectedOnAndroid) { - assertFalse(StandardNames.IS_RI); - } - try { - getSSLSocket(InetAddress.getLocalHost(), sport, - InetAddress.getLocalHost(), Integer.MAX_VALUE); - fail(); - } catch (IllegalArgumentException expectedOnAndroid) { - assertFalse(StandardNames.IS_RI); - } - } - - /** - * javax.net.ssl.SSLSocket#SSLSocket(String host, int port) - */ - public void testConstructor_StringI() throws Exception { - int sport = startServer("Cons String,I"); - int[] invalidPort = {-1, Integer.MIN_VALUE, 65536, Integer.MAX_VALUE}; - - SSLSocket ssl = getSSLSocket(InetAddress.getLocalHost().getHostName(), sport); - assertNotNull(ssl); - assertEquals(sport, ssl.getPort()); - ssl.close(); - - try { - getSSLSocket("localhost", 8082); - fail(); - } catch (IOException expected) { - } - - for (int i = 0; i < invalidPort.length; i++) { - try { - getSSLSocket(InetAddress.getLocalHost().getHostName(), invalidPort[i]); - fail(); - } catch (IllegalArgumentException expected) { - } - } - - try { - getSSLSocket("bla-bla", sport); - fail(); - } catch (UnknownHostException expected) { - } - } - - /** - * javax.net.ssl.SSLSocket#SSLSocket(String host, int port, InetAddress clientAddress, - * int clientPort) - */ - public void testConstructor_StringIInetAddressI() throws Exception { - int sport = startServer("Cons String,I,InetAddress,I"); - int[] invalidPort = {-1, Integer.MIN_VALUE, 65536, Integer.MAX_VALUE}; - - SSLSocket ssl = getSSLSocket(InetAddress.getLocalHost().getHostName(), sport, - InetAddress.getLocalHost(), 0); - assertNotNull(ssl); - assertEquals(sport, ssl.getPort()); - - try { - getSSLSocket(InetAddress.getLocalHost().getHostName(), 8081, InetAddress.getLocalHost(), 8082); - fail(); - } catch (IOException expected) { - } - - for (int i = 0; i < invalidPort.length; i++) { - try { - getSSLSocket(InetAddress.getLocalHost().getHostName(), invalidPort[i], - InetAddress.getLocalHost(), 0); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - getSSLSocket(InetAddress.getLocalHost().getHostName(), sport, - InetAddress.getLocalHost(), invalidPort[i]); - fail(); - } catch (IllegalArgumentException expected) { - } - } - - try { - getSSLSocket("bla-bla", sport, InetAddress.getLocalHost(), 0); - fail(); - } catch (UnknownHostException expected) { - } - } - - public void test_creationStressTest() throws Exception { - // Test the default codepath, which uses /dev/urandom. - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(null, null, null); - for (int i = 0; i < 2048; ++i) { - sslContext.getSocketFactory().createSocket().close(); - } - - // Test the other codepath, which copies a seed from a byte[]. - sslContext.init(null, null, new SecureRandom()); - for (int i = 0; i < 2048; ++i) { - sslContext.getSocketFactory().createSocket().close(); - } - } - - /** - * javax.net.ssl.SSLSocket#addHandshakeCompletedListener(HandshakeCompletedListener listener) - */ - @AndroidOnly("RI doesn't throw the specified IAE") - public void test_addHandshakeCompletedListener() throws IOException { - SSLSocket ssl = getSSLSocket(); - HandshakeCompletedListener ls = new HandshakeCL(); - try { - ssl.addHandshakeCompletedListener(null); - fail(); - } catch (IllegalArgumentException expected) { - } - ssl.addHandshakeCompletedListener(ls); - ssl.close(); - } - - /** - * javax.net.ssl.SSLSocket#removeHandshakeCompletedListener(HandshakeCompletedListener listener) - */ - public void test_removeHandshakeCompletedListener() throws IOException { - SSLSocket ssl = getSSLSocket(); - HandshakeCompletedListener ls = new HandshakeCL(); - try { - ssl.removeHandshakeCompletedListener(null); - fail(); - } catch (IllegalArgumentException expected) { - } - - try { - ssl.removeHandshakeCompletedListener(ls); - } catch (IllegalArgumentException expected) { - } - - ssl.addHandshakeCompletedListener(ls); - ssl.removeHandshakeCompletedListener(ls); - ssl.close(); - } - - /** - * javax.net.ssl.SSLSocket#setEnableSessionCreation(boolean flag) - * javax.net.ssl.SSLSocket#getEnableSessionCreation() - */ - public void test_EnableSessionCreation() throws IOException { - SSLSocket ssl = getSSLSocket(); - assertTrue(ssl.getEnableSessionCreation()); - ssl.setEnableSessionCreation(false); - assertFalse(ssl.getEnableSessionCreation()); - ssl.setEnableSessionCreation(true); - assertTrue(ssl.getEnableSessionCreation()); - ssl.close(); - } - - /** - * javax.net.ssl.SSLSocket#setNeedClientAuth(boolean need) - * javax.net.ssl.SSLSocket#getNeedClientAuthCreation() - */ - public void test_NeedClientAuth() throws UnknownHostException, IOException { - SSLSocket ssl = getSSLSocket(); - ssl.setNeedClientAuth(true); - assertTrue(ssl.getNeedClientAuth()); - ssl.setNeedClientAuth(false); - assertFalse(ssl.getNeedClientAuth()); - ssl.close(); - } - - /** - * javax.net.ssl.SSLSocket#setWantClientAuth(boolean want) - * javax.net.ssl.SSLSocket#getWantClientAuthCreation() - */ - public void test_WantClientAuth() throws UnknownHostException, IOException { - SSLSocket ssl = getSSLSocket(); - ssl.setWantClientAuth(true); - assertTrue(ssl.getWantClientAuth()); - ssl.setWantClientAuth(false); - assertFalse(ssl.getWantClientAuth()); - ssl.close(); - } - - /** - * javax.net.ssl.SSLSocket#getSupportedProtocols() - */ - public void test_getSupportedProtocols() throws IOException { - SSLSocket ssl = getSSLSocket(); - String[] res = ssl.getSupportedProtocols(); - assertTrue("No supported protocols found", res.length > 0); - ssl.close(); - } - - /** - * javax.net.ssl.SSLSocket#getEnabledProtocols() - * javax.net.ssl.SSLSocket#setEnabledProtocols(String[] protocols) - */ - public void test_EnabledProtocols() throws IOException { - SSLSocket ssl = getSSLSocket(); - try { - ssl.setEnabledProtocols(null); - fail(); - } catch (IllegalArgumentException expected) { - } - ssl.setEnabledProtocols(new String[] {}); - try { - ssl.setEnabledProtocols(new String[] {"blubb"}); - fail(); - } catch (IllegalArgumentException expected) { - } - ssl.setEnabledProtocols(ssl.getEnabledProtocols()); - String[] res = ssl.getEnabledProtocols(); - assertEquals("no enabled protocols set", - ssl.getEnabledProtocols().length, res.length); - ssl.close(); - } - - /** - * javax.net.ssl.SSLSocket#getSession() - */ - public void test_getSession() throws IOException { - SSLSocket ssl = getSSLSocket(); - assertNotNull(ssl.getSession()); - ssl.close(); - } - - /** - * javax.net.ssl.SSLSocket#getSupportedCipherSuites() - */ - public void test_getSupportedCipherSuites() throws IOException { - SSLSocket ssl = getSSLSocket(); - String[] res = ssl.getSupportedCipherSuites(); - assertTrue("no supported cipher suites", res.length > 0); - ssl.close(); - } - - /** - * javax.net.ssl.SSLSocket#getEnabledCipherSuites() - * javax.net.ssl.SSLSocket#setEnabledCipherSuites(String[] suites) - */ - public void test_EnabledCipherSuites() throws IOException { - SSLSocket ssl = getSSLSocket(); - try { - ssl.setEnabledCipherSuites(null); - fail(); - } catch (IllegalArgumentException expected) { - } - ssl.setEnabledCipherSuites(new String[] {}); - try { - ssl.setEnabledCipherSuites(new String[] {"blubb"}); - fail(); - } catch (IllegalArgumentException expected) { - } - ssl.setEnabledCipherSuites(ssl.getSupportedCipherSuites()); - String[] res = ssl.getEnabledCipherSuites(); - assertNotNull("NULL result", res); - assertEquals("not all supported cipher suites were enabled", - Arrays.asList(ssl.getSupportedCipherSuites()), - Arrays.asList(res)); - ssl.close(); - } - - /** - * javax.net.ssl.SSLSocket#getUseClientMode() - * javax.net.ssl.SSLSocket#setUseClientMode(boolean mode) - */ - public void test_UseClientMode() throws IOException { - SSLSocket ssl = getSSLSocket(); - assertTrue(ssl.getUseClientMode()); - ssl.setUseClientMode(false); - assertFalse(ssl.getUseClientMode()); - ssl.close(); - - ssl = getSSLSocket("localhost", startServer("UseClientMode")); - try { - ssl.startHandshake(); - } catch (IOException ioe) { - //fail(ioe + " was thrown for method startHandshake()"); - } - try { - ssl.setUseClientMode(false); - fail(); - } catch (IllegalArgumentException expected) { - } - ssl.close(); - } - - /** - * javax.net.ssl.SSLSocket#startHandshake() - */ - public void test_startHandshake() throws IOException { - SSLSocket ssl = getSSLSocket(); - try { - ssl.startHandshake(); - fail(); - } catch (IOException expected) { - } - ssl.close(); - } - - private boolean useBKS = !StandardNames.IS_RI; - - private String PASSWORD = "android"; - - private boolean serverReady = false; - - /** - * Defines the keystore contents for the server, BKS version. Holds just a - * single self-generated key. The subject name is "Test Server". - */ - private static final String SERVER_KEYS_BKS = "" - + "AAAAAQAAABQDkebzoP1XwqyWKRCJEpn/t8dqIQAABDkEAAVteWtleQAAARpYl20nAAAAAQAFWC41" - + "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU1jANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET" - + "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV" - + "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMB4XDTA4MDYwNTExNTgxNFoXDTA4MDkw" - + "MzExNTgxNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U" - + "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IFNlcnZl" - + "cjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0LIdKaIr9/vsTq8BZlA3R+NFWRaH4lGsTAQy" - + "DPMF9ZqEDOaL6DJuu0colSBBBQ85hQTPa9m9nyJoN3pEi1hgamqOvQIWcXBk+SOpUGRZZFXwniJV" - + "zDKU5nE9MYgn2B9AoiH3CSuMz6HRqgVaqtppIe1jhukMc/kHVJvlKRNy9XMCAwEAATANBgkqhkiG" - + "9w0BAQUFAAOBgQC7yBmJ9O/eWDGtSH9BH0R3dh2NdST3W9hNZ8hIa8U8klhNHbUCSSktZmZkvbPU" - + "hse5LI3dh6RyNDuqDrbYwcqzKbFJaq/jX9kCoeb3vgbQElMRX8D2ID1vRjxwlALFISrtaN4VpWzV" - + "yeoHPW4xldeZmoVtjn8zXNzQhLuBqX2MmAAAAqwAAAAUvkUScfw9yCSmALruURNmtBai7kQAAAZx" - + "4Jmijxs/l8EBaleaUru6EOPioWkUAEVWCxjM/TxbGHOi2VMsQWqRr/DZ3wsDmtQgw3QTrUK666sR" - + "MBnbqdnyCyvM1J2V1xxLXPUeRBmR2CXorYGF9Dye7NkgVdfA+9g9L/0Au6Ugn+2Cj5leoIgkgApN" - + "vuEcZegFlNOUPVEs3SlBgUF1BY6OBM0UBHTPwGGxFBBcetcuMRbUnu65vyDG0pslT59qpaR0TMVs" - + "P+tcheEzhyjbfM32/vwhnL9dBEgM8qMt0sqF6itNOQU/F4WGkK2Cm2v4CYEyKYw325fEhzTXosck" - + "MhbqmcyLab8EPceWF3dweoUT76+jEZx8lV2dapR+CmczQI43tV9btsd1xiBbBHAKvymm9Ep9bPzM" - + "J0MQi+OtURL9Lxke/70/MRueqbPeUlOaGvANTmXQD2OnW7PISwJ9lpeLfTG0LcqkoqkbtLKQLYHI" - + "rQfV5j0j+wmvmpMxzjN3uvNajLa4zQ8l0Eok9SFaRr2RL0gN8Q2JegfOL4pUiHPsh64WWya2NB7f" - + "V+1s65eA5ospXYsShRjo046QhGTmymwXXzdzuxu8IlnTEont6P4+J+GsWk6cldGbl20hctuUKzyx" - + "OptjEPOKejV60iDCYGmHbCWAzQ8h5MILV82IclzNViZmzAapeeCnexhpXhWTs+xDEYSKEiG/camt" - + "bhmZc3BcyVJrW23PktSfpBQ6D8ZxoMfF0L7V2GQMaUg+3r7ucrx82kpqotjv0xHghNIm95aBr1Qw" - + "1gaEjsC/0wGmmBDg1dTDH+F1p9TInzr3EFuYD0YiQ7YlAHq3cPuyGoLXJ5dXYuSBfhDXJSeddUkl" - + "k1ufZyOOcskeInQge7jzaRfmKg3U94r+spMEvb0AzDQVOKvjjo1ivxMSgFRZaDb/4qw="; - - /** - * Defines the keystore contents for the server, JKS version. Holds just a - * single self-generated key. The subject name is "Test Server". - */ - private static final String SERVER_KEYS_JKS = "" - + "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFfBeAAAArowggK2MA4GCisGAQQBKgIRAQEFAASC" - + "AqI2kp5XjnF8YZkhcF92YsJNQkvsmH7zqMM87j23zSoV4DwyE3XeC/gZWq1ToScIhoqZkzlbWcu4" - + "T/Zfc/DrfGk/rKbBL1uWKGZ8fMtlZk8KoAhxZk1JSyJvdkyKxqmzUbxk1OFMlN2VJNu97FPVH+du" - + "dvjTvmpdoM81INWBW/1fZJeQeDvn4mMbbe0IxgpiLnI9WSevlaDP/sm1X3iO9yEyzHLL+M5Erspo" - + "Cwa558fOu5DdsICMXhvDQxjWFKFhPHnKtGe+VvwkG9/bAaDgx3kfhk0w5zvdnkKb+8Ed9ylNRzdk" - + "ocAa/mxlMTOsTvDKXjjsBupNPIIj7OP4GNnZaxkJjSs98pEO67op1GX2qhy6FSOPNuq8k/65HzUc" - + "PYn6voEeh6vm02U/sjEnzRevQ2+2wXoAdp0EwtQ/DlMe+NvcwPGWKuMgX4A4L93DZGb04N2VmAU3" - + "YLOtZwTO0LbuWrcCM/q99G/7LcczkxIVrO2I/rh8RXVczlf9QzcrFObFv4ATuspWJ8xG7DhsMbnk" - + "rT94Pq6TogYeoz8o8ZMykesAqN6mt/9+ToIemmXv+e+KU1hI5oLwWMnUG6dXM6hIvrULY6o+QCPH" - + "172YQJMa+68HAeS+itBTAF4Clm/bLn6reHCGGU6vNdwU0lYldpiOj9cB3t+u2UuLo6tiFWjLf5Zs" - + "EQJETd4g/EK9nHxJn0GAKrWnTw7pEHQJ08elzUuy04C/jEEG+4QXU1InzS4o/kR0Sqz2WTGDoSoq" - + "ewuPRU5bzQs/b9daq3mXrnPtRBL6HfSDAdpTK76iHqLCGdqx3avHjVSBm4zFvEuYBCev+3iKOBmg" - + "yh7eQRTjz4UOWfy85omMBr7lK8PtfVBDzOXpasxS0uBgdUyBDX4tO6k9jZ8a1kmQRQAAAAEABVgu" - + "NTA5AAACSDCCAkQwggGtAgRIR8SKMA0GCSqGSIb3DQEBBAUAMGkxCzAJBgNVBAYTAlVTMRMwEQYD" - + "VQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzANBgNVBAoTBkdvb2dsZTEQMA4GA1UECxMH" - + "QW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBTZXJ2ZXIwHhcNMDgwNjA1MTA0ODQyWhcNMDgwOTAzMTA0" - + "ODQyWjBpMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8w" - + "DQYDVQQKEwZHb29nbGUxEDAOBgNVBAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMIGf" - + "MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwoC6chqCI84rj1PrXuJgbiit4EV909zR6N0jNlYfg" - + "itwB39bP39wH03rFm8T59b3mbSptnGmCIpLZn25KPPFsYD3JJ+wFlmiUdEP9H05flfwtFQJnw9uT" - + "3rRIdYVMPcQ3RoZzwAMliGr882I2thIDbA6xjGU/1nRIdvk0LtxH3QIDAQABMA0GCSqGSIb3DQEB" - + "BAUAA4GBAJn+6YgUlY18Ie+0+Vt8oEi81DNi/bfPrAUAh63fhhBikx/3R9dl3wh09Z6p7cIdNxjW" - + "n2ll+cRW9eqF7z75F0Omm0C7/KAEPjukVbszmzeU5VqzkpSt0j84YWi+TfcHRrfvhLbrlmGITVpY" - + "ol5pHLDyqGmDs53pgwipWqsn/nEXEBgj3EoqPeqHbDf7YaP8h/5BSt0="; - - protected int startServer(String name) { - String keys = useBKS ? SERVER_KEYS_BKS : SERVER_KEYS_JKS; - TestServer server = new TestServer(true, keys); - Thread serverThread = new Thread(server); - serverThread.start(); - try { - while (!serverReady) { - Exception e = server.getException(); - if (e != null) { - throw new AssertionError(e); - } - Thread.currentThread().sleep(50); - } - // give the server 100 millis to accept - Thread.currentThread().sleep(100); - } catch (InterruptedException ignore) { - } - return server.sport; - } - - /** - * Implements a test SSL socket server. It wait for a connection on a given - * port, requests client authentication (if specified), and read 256 bytes - * from the socket. - */ - class TestServer implements Runnable { - - public static final int CLIENT_AUTH_NONE = 0; - - public static final int CLIENT_AUTH_WANTED = 1; - - public static final int CLIENT_AUTH_NEEDED = 2; - - private TestTrustManager trustManager; - - private Exception exception; - - String keys; - - private boolean provideKeys; - - int sport; - - public TestServer(boolean provideKeys, String keys) { - this.keys = keys; - this.provideKeys = provideKeys; - - trustManager = new TestTrustManager(); - } - - public void run() { - try { - KeyManager[] keyManagers = provideKeys ? getKeyManagers(keys) : null; - TrustManager[] trustManagers = new TrustManager[] { trustManager }; - - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyManagers, trustManagers, null); - - SSLServerSocket serverSocket = (SSLServerSocket) - sslContext.getServerSocketFactory().createServerSocket(); - try { - serverSocket.bind(new InetSocketAddress(0)); - sport = serverSocket.getLocalPort(); - serverReady = true; - - SSLSocket clientSocket = (SSLSocket)serverSocket.accept(); - - try { - InputStream stream = clientSocket.getInputStream(); - try { - for (int i = 0; i < 256; i++) { - int j = stream.read(); - if (i != j) { - throw new RuntimeException("Error reading socket, expected " + i - + ", got " + j); - } - } - } finally { - stream.close(); - } - } finally { - clientSocket.close(); - } - } finally { - serverSocket.close(); - } - } catch (Exception ex) { - exception = ex; - } - } - - public Exception getException() { - return exception; - } - - public X509Certificate[] getChain() { - return trustManager.getChain(); - } - - } - - /** - * Loads a keystore from a base64-encoded String. Returns the KeyManager[] - * for the result. - */ - private KeyManager[] getKeyManagers(String keys) throws Exception { - byte[] bytes = Base64.decode(keys.getBytes()); - InputStream inputStream = new ByteArrayInputStream(bytes); - - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(inputStream, PASSWORD.toCharArray()); - inputStream.close(); - - String algorithm = KeyManagerFactory.getDefaultAlgorithm(); - KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm); - keyManagerFactory.init(keyStore, PASSWORD.toCharArray()); - - return keyManagerFactory.getKeyManagers(); - } - - private SSLSocket getSSLSocket() throws IOException { - return (SSLSocket) SSLSocketFactory.getDefault().createSocket(); - } - - private SSLSocket getSSLSocket(InetAddress host, int port) throws IOException { - return (SSLSocket) SSLSocketFactory.getDefault().createSocket(host, port); - } - - private SSLSocket getSSLSocket(String host, int port) throws UnknownHostException, IOException { - return (SSLSocket) SSLSocketFactory.getDefault().createSocket(host, port); - } - - private SSLSocket getSSLSocket(InetAddress host, int port, InetAddress localHost, int localPort) - throws IOException { - return (SSLSocket) SSLSocketFactory.getDefault().createSocket(host, - port, - localHost, - localPort); - } - - private SSLSocket getSSLSocket(String host, int port, InetAddress localHost, int localPort) - throws UnknownHostException, IOException { - return (SSLSocket) SSLSocketFactory.getDefault().createSocket(host, - port, - localHost, - localPort); - } -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/TrustManagerFactory1Test.java b/luni/src/test/java/tests/api/javax/net/ssl/TrustManagerFactory1Test.java deleted file mode 100644 index 23b24e4..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/TrustManagerFactory1Test.java +++ /dev/null @@ -1,519 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.net.ssl; - -import dalvik.annotation.KnownFailure; -import java.io.IOException; -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.PublicKey; -import java.security.Security; -import java.security.cert.CertificateException; -import java.security.cert.PKIXBuilderParameters; -import java.security.cert.TrustAnchor; -import java.security.cert.X509CertSelector; -import java.util.HashSet; -import java.util.Set; -import javax.net.ssl.CertPathTrustManagerParameters; -import javax.net.ssl.ManagerFactoryParameters; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.TrustManagerFactorySpi; -import junit.framework.TestCase; -import org.apache.harmony.security.tests.support.SpiEngUtils; -import org.apache.harmony.security.tests.support.TestKeyPair; -import org.apache.harmony.xnet.tests.support.MyTrustManagerFactorySpi; - -/** - * Tests for <code>TrustManagerFactory</code> class constructors and methods. - * - */ -public class TrustManagerFactory1Test extends TestCase { - - private static final String srvTrustManagerFactory = "TrustManagerFactory"; - - private static final String[] invalidValues = SpiEngUtils.invalidValues; - - private static String DEFAULT_ALGORITHM; - private static String DEFAULT_PROVIDER_NAME; - private static Provider DEFAULT_PROVIDER; - private static String[] VALID_VALUES; - - private static String getDefaultAlgorithm() { - init(); - return DEFAULT_ALGORITHM; - } - private static String getDefaultProviderName() { - init(); - return DEFAULT_PROVIDER_NAME; - } - private static Provider getDefaultProvider() { - init(); - return DEFAULT_PROVIDER; - } - private static String[] getValidValues() { - init(); - return VALID_VALUES; - } - - private static synchronized void init() { - if (DEFAULT_ALGORITHM != null) { - return; - } - DEFAULT_ALGORITHM = Security.getProperty("ssl.TrustManagerFactory.algorithm"); - assertNotNull(DEFAULT_ALGORITHM); - DEFAULT_PROVIDER = SpiEngUtils.isSupport(DEFAULT_ALGORITHM, srvTrustManagerFactory); - DEFAULT_PROVIDER_NAME = DEFAULT_PROVIDER.getName(); - VALID_VALUES = new String[] { DEFAULT_ALGORITHM, - DEFAULT_ALGORITHM.toUpperCase(), - DEFAULT_ALGORITHM.toLowerCase() }; - } - - private static TrustManagerFactory[] createTMFac() throws Exception { - return new TrustManagerFactory[] { - TrustManagerFactory.getInstance(getDefaultAlgorithm()), - TrustManagerFactory.getInstance(getDefaultAlgorithm(), getDefaultProvider()), - TrustManagerFactory.getInstance(getDefaultAlgorithm(), getDefaultProviderName()) - }; - } - - public void test_ConstructorLjavax_net_ssl_TrustManagerFactorySpiLjava_security_ProviderLjava_lang_String() - throws NoSuchAlgorithmException { - TrustManagerFactorySpi spi = new MyTrustManagerFactorySpi(); - TrustManagerFactory tmF = new myTrustManagerFactory(spi, getDefaultProvider(), - getDefaultAlgorithm()); - assertTrue("Not CertStore object", tmF instanceof TrustManagerFactory); - assertEquals("Incorrect algorithm", tmF.getAlgorithm(), - getDefaultAlgorithm()); - assertEquals("Incorrect provider", tmF.getProvider(), getDefaultProvider()); - assertNull("Incorrect result", tmF.getTrustManagers()); - - tmF = new myTrustManagerFactory(null, null, null); - assertTrue("Not CertStore object", tmF instanceof TrustManagerFactory); - assertNull("Provider must be null", tmF.getProvider()); - assertNull("Algorithm must be null", tmF.getAlgorithm()); - try { - tmF.getTrustManagers(); - fail("NullPointerException must be thrown"); - } catch (NullPointerException e) { - } - } - - /** - * Test for <code>getAlgorithm()</code> method - * Assertion: returns the algorithm name of this object - * @throws NoSuchAlgorithmException - * @throws NoSuchProviderException - */ - public void test_getAlgorithm() - throws NoSuchAlgorithmException, NoSuchProviderException { - assertEquals("Incorrect algorithm", - getDefaultAlgorithm(), - TrustManagerFactory - .getInstance(getDefaultAlgorithm()).getAlgorithm()); - assertEquals("Incorrect algorithm", - getDefaultAlgorithm(), - TrustManagerFactory - .getInstance(getDefaultAlgorithm(), getDefaultProviderName()) - .getAlgorithm()); - assertEquals("Incorrect algorithm", - getDefaultAlgorithm(), - TrustManagerFactory.getInstance(getDefaultAlgorithm(), getDefaultProvider()) - .getAlgorithm()); - } - - /** - * Test for <code>getDefaultAlgorithm()</code> method - * Assertion: returns value which is specifoed in security property - */ - public void test_getDefaultAlgorithm() { - String def = TrustManagerFactory.getDefaultAlgorithm(); - if (getDefaultAlgorithm() == null) { - assertNull("DefaultAlgorithm must be null", def); - } else { - assertEquals("Invalid default algorithm", def, getDefaultAlgorithm()); - } - String defA = "Proba.trustmanagerfactory.defaul.type"; - Security.setProperty("ssl.TrustManagerFactory.algorithm", defA); - assertEquals("Incorrect getDefaultAlgorithm()", - TrustManagerFactory.getDefaultAlgorithm(), defA); - if (def == null) { - def = ""; - } - Security.setProperty("ssl.TrustManagerFactory.algorithm", def); - assertEquals("Incorrect getDefaultAlgorithm()", - TrustManagerFactory.getDefaultAlgorithm(), def); - } - - /** - * Test for <code>getInstance(String algorithm)</code> method - * Assertions: returns security property "ssl.TrustManagerFactory.algorithm"; - * returns instance of TrustManagerFactory - */ - public void test_getInstanceLjava_lang_String01() throws NoSuchAlgorithmException { - for (String validValue : getValidValues()) { - TrustManagerFactory trustMF = TrustManagerFactory.getInstance(validValue); - assertTrue("Not TrustManagerFactory object", - trustMF instanceof TrustManagerFactory); - assertEquals("Invalid algorithm", trustMF.getAlgorithm(), validValue); - } - } - - /** - * Test for <code>getInstance(String algorithm)</code> method - * Assertion: - * throws NullPointerException when algorithm is null; - * throws NoSuchAlgorithmException when algorithm is not correct; - */ - public void test_getInstanceLjava_lang_String02() { - try { - TrustManagerFactory.getInstance(null); - fail(); - } catch (NoSuchAlgorithmException expected) { - } catch (NullPointerException expected) { - } - for (int i = 0; i < invalidValues.length; i++) { - try { - TrustManagerFactory.getInstance(invalidValues[i]); - fail("NoSuchAlgorithmException was not thrown as expected for algorithm: " - .concat(invalidValues[i])); - } catch (NoSuchAlgorithmException e) { - } - } - } - - /** - * Test for <code>getInstance(String algorithm, String provider)</code> - * method - * Assertion: throws IllegalArgumentException when provider is null - * or empty - */ - public void test_getInstanceLjava_lang_StringLjava_lang_String01() throws Exception { - for (String validValue : getValidValues()) { - try { - TrustManagerFactory.getInstance(validValue, (String) null); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - TrustManagerFactory.getInstance(validValue, ""); - fail(); - } catch (IllegalArgumentException expected) { - } - } - } - - /** - * Test for <code>getInstance(String algorithm, String provider)</code> - * method - * Assertion: - * throws NullPointerException when algorithm is null; - * throws NoSuchAlgorithmException when algorithm is not correct; - */ - public void test_getInstanceLjava_lang_StringLjava_lang_String02() throws Exception { - try { - TrustManagerFactory.getInstance(null, getDefaultProviderName()); - fail(); - } catch (NoSuchAlgorithmException expected) { - } catch (NullPointerException expected) { - } - for (int i = 0; i < invalidValues.length; i++) { - try { - TrustManagerFactory.getInstance(invalidValues[i], - getDefaultProviderName()); - fail("NoSuchAlgorithmException must be thrown (algorithm: " - .concat(invalidValues[i]).concat(")")); - } catch (NoSuchAlgorithmException e) { - } - } - } - - /** - * Test for <code>getInstance(String algorithm, String provider)</code> - * method - * Assertion: throws NoSuchProviderException when provider has - * invalid value - */ - public void test_getInstanceLjava_lang_StringLjava_lang_String03() throws Exception { - for (String invalidValue : invalidValues) { - for (String validValue : getValidValues()) { - try { - TrustManagerFactory.getInstance(validValue, invalidValue); - fail("NoSuchProviderException must be thrown (algorithm: " - .concat(validValue).concat(" provider: ") - .concat(invalidValue).concat(")")); - } catch (NoSuchProviderException expected) { - assertFalse("".equals(invalidValue)); - } catch (IllegalArgumentException expected) { - assertEquals("", invalidValue); - } - } - } - } - - /** - * Test for <code>getInstance(String algorithm, String provider)</code> - * method - * Assertion: returns instance of TrustManagerFactory - */ - public void test_getInstanceLjava_lang_StringLjava_lang_String04() throws Exception { - for (String validValue : getValidValues()) { - TrustManagerFactory trustMF = TrustManagerFactory.getInstance(validValue, - getDefaultProviderName()); - assertTrue("Not TrustManagerFactory object", - trustMF instanceof TrustManagerFactory); - assertEquals("Invalid algorithm", trustMF.getAlgorithm(), validValue); - assertEquals("Invalid provider", trustMF.getProvider(), getDefaultProvider()); - } - } - - /** - * Test for <code>getInstance(String algorithm, Provider provider)</code> - * method - * Assertion: throws IllegalArgumentException when provider is null - */ - public void test_getInstanceLjava_lang_StringLjava_security_Provider01() throws Exception { - for (String validValue : getValidValues()) { - try { - TrustManagerFactory.getInstance(validValue, (Provider) null); - } catch (IllegalArgumentException expected) { - } - } - } - - /** - * Test for <code>getInstance(String algorithm, Provider provider)</code> - * method - * Assertion: - * throws NullPointerException when algorithm is null; - * throws NoSuchAlgorithmException when algorithm is not correct; - */ - public void test_getInstanceLjava_lang_StringLjava_security_Provider02() { - try { - TrustManagerFactory.getInstance(null, getDefaultProvider()); - fail(""); - } catch (NoSuchAlgorithmException expected) { - } catch (NullPointerException expected) { - } - for (int i = 0; i < invalidValues.length; i++) { - try { - TrustManagerFactory.getInstance(invalidValues[i], - getDefaultProvider()); - fail("NoSuchAlgorithmException must be thrown (algorithm: " - .concat(invalidValues[i]).concat(")")); - } catch (NoSuchAlgorithmException e) { - } - } - } - - /** - * Test for <code>getInstance(String algorithm, Provider provider)</code> - * method - * Assertion: returns instance of TrustManagerFactory - */ - public void test_getInstanceLjava_lang_StringLjava_security_Provider03() throws Exception { - for (String validValue : getValidValues()) { - TrustManagerFactory trustMF = TrustManagerFactory.getInstance(validValue, - getDefaultProvider()); - assertTrue("Not TrustManagerFactory object", - trustMF instanceof TrustManagerFactory); - assertEquals("Invalid algorithm", trustMF.getAlgorithm(), validValue); - assertEquals("Invalid provider", trustMF.getProvider(), getDefaultProvider()); - } - } - - /** - * Test for <code>getProvider()</code> - * @throws NoSuchAlgorithmException - * @throws NoSuchProviderException - */ - public void test_getProvider() - throws NoSuchAlgorithmException, NoSuchProviderException { - assertEquals("Incorrect provider", - getDefaultProvider(), - TrustManagerFactory - .getInstance(getDefaultAlgorithm()).getProvider()); - assertEquals("Incorrect provider", - getDefaultProvider(), - TrustManagerFactory - .getInstance(getDefaultAlgorithm(), getDefaultProviderName()) - .getProvider()); - assertEquals("Incorrect provider", - getDefaultProvider(), - TrustManagerFactory.getInstance(getDefaultAlgorithm(), getDefaultProvider()) - .getProvider()); - } - - /** - * Test for <code>geTrustManagers()</code> - * @throws KeyStoreException - * @throws IOException - * @throws CertificateException - * @throws NoSuchAlgorithmException - */ - public void test_getTrustManagers() { - try { - TrustManagerFactory trustMF = TrustManagerFactory.getInstance(getDefaultAlgorithm()); - KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); - ks.load(null, null); - trustMF.init(ks); - TrustManager[] tm = trustMF.getTrustManagers(); - assertNotNull("Result has not be null", tm); - assertTrue("Length of result TrustManager array should not be 0", - (tm.length > 0)); - } catch (Exception ex) { - fail("Unexpected exception " + ex.toString()); - } - } - - /** - * Test for <code>init(KeyStore keyStore)</code> - * Assertion: call method with null parameter - */ - public void test_initLjava_security_KeyStore_01() throws Exception { - KeyStore ksNull = null; - TrustManagerFactory[] trustMF = createTMFac(); - assertNotNull("TrustManagerFactory objects were not created", trustMF); - // null parameter - try { - trustMF[0].init(ksNull); - } catch (Exception ex) { - fail(ex + " unexpected exception was thrown for null parameter"); - } - } - - /** - * Test for <code>init(KeyStore keyStore)</code> - * Assertion: call method with not null parameter - */ - public void test_initLjava_security_KeyStore_02() throws Exception { - KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); - TrustManagerFactory[] trustMF = createTMFac(); - assertNotNull("TrustManagerFactory objects were not created", trustMF); - - // not null parameter - trustMF[0].init(ks); - } - - /** - * Test for <code>init(ManagerFactoryParameters params)</code> - * Assertion: - * throws InvalidAlgorithmParameterException when params is null - */ - @KnownFailure("ManagerFactoryParameters object is not supported " - + "and InvalidAlgorithmParameterException was thrown.") - public void test_initLjavax_net_ssl_ManagerFactoryParameters() throws Exception { - ManagerFactoryParameters par = null; - TrustManagerFactory[] trustMF = createTMFac(); - assertNotNull("TrustManagerFactory objects were not created", trustMF); - for (int i = 0; i < trustMF.length; i++) { - try { - trustMF[i].init(par); - fail("InvalidAlgorithmParameterException must be thrown"); - } catch (InvalidAlgorithmParameterException e) { - } - } - - String keyAlg = "DSA"; - String validCaNameRfc2253 = ("CN=Test CA," - + "OU=Testing Division," - + "O=Test It All," - + "L=Test Town," - + "ST=Testifornia," - + "C=Testland"); - - try { - KeyStore kStore = KeyStore.getInstance(KeyStore.getDefaultType()); - kStore.load(null, null); - PublicKey pk = new TestKeyPair(keyAlg).getPublic(); - TrustAnchor ta = new TrustAnchor(validCaNameRfc2253, pk, getFullEncoding()); - Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>(); - trustAnchors.add(ta); - X509CertSelector xcs = new X509CertSelector(); - PKIXBuilderParameters pkixBP = new PKIXBuilderParameters(trustAnchors, xcs); - CertPathTrustManagerParameters cptmp = new CertPathTrustManagerParameters(pkixBP); - TrustManagerFactory tmf = TrustManagerFactory.getInstance(getDefaultAlgorithm()); - try { - tmf.init(cptmp); - } catch (Exception ex) { - fail(ex + " was thrown for init(ManagerFactoryParameters spec)"); - } - } catch (Exception e) { - fail("Unexpected exception for configuration: " + e); - } - - } - - private static final byte[] getFullEncoding() { - // DO NOT MODIFY! - return new byte[] { - (byte)0x30,(byte)0x81,(byte)0x8c,(byte)0xa0, - (byte)0x44,(byte)0x30,(byte)0x16,(byte)0x86, - (byte)0x0e,(byte)0x66,(byte)0x69,(byte)0x6c, - (byte)0x65,(byte)0x3a,(byte)0x2f,(byte)0x2f, - (byte)0x66,(byte)0x6f,(byte)0x6f,(byte)0x2e, - (byte)0x63,(byte)0x6f,(byte)0x6d,(byte)0x80, - (byte)0x01,(byte)0x00,(byte)0x81,(byte)0x01, - (byte)0x01,(byte)0x30,(byte)0x16,(byte)0x86, - (byte)0x0e,(byte)0x66,(byte)0x69,(byte)0x6c, - (byte)0x65,(byte)0x3a,(byte)0x2f,(byte)0x2f, - (byte)0x62,(byte)0x61,(byte)0x72,(byte)0x2e, - (byte)0x63,(byte)0x6f,(byte)0x6d,(byte)0x80, - (byte)0x01,(byte)0x00,(byte)0x81,(byte)0x01, - (byte)0x01,(byte)0x30,(byte)0x12,(byte)0x86, - (byte)0x0a,(byte)0x66,(byte)0x69,(byte)0x6c, - (byte)0x65,(byte)0x3a,(byte)0x2f,(byte)0x2f, - (byte)0x6d,(byte)0x75,(byte)0x75,(byte)0x80, - (byte)0x01,(byte)0x00,(byte)0x81,(byte)0x01, - (byte)0x01,(byte)0xa1,(byte)0x44,(byte)0x30, - (byte)0x16,(byte)0x86,(byte)0x0e,(byte)0x68, - (byte)0x74,(byte)0x74,(byte)0x70,(byte)0x3a, - (byte)0x2f,(byte)0x2f,(byte)0x66,(byte)0x6f, - (byte)0x6f,(byte)0x2e,(byte)0x63,(byte)0x6f, - (byte)0x6d,(byte)0x80,(byte)0x01,(byte)0x00, - (byte)0x81,(byte)0x01,(byte)0x01,(byte)0x30, - (byte)0x16,(byte)0x86,(byte)0x0e,(byte)0x68, - (byte)0x74,(byte)0x74,(byte)0x70,(byte)0x3a, - (byte)0x2f,(byte)0x2f,(byte)0x62,(byte)0x61, - (byte)0x72,(byte)0x2e,(byte)0x63,(byte)0x6f, - (byte)0x6d,(byte)0x80,(byte)0x01,(byte)0x00, - (byte)0x81,(byte)0x01,(byte)0x01,(byte)0x30, - (byte)0x12,(byte)0x86,(byte)0x0a,(byte)0x68, - (byte)0x74,(byte)0x74,(byte)0x70,(byte)0x3a, - (byte)0x2f,(byte)0x2f,(byte)0x6d,(byte)0x75, - (byte)0x75,(byte)0x80,(byte)0x01,(byte)0x00, - (byte)0x81,(byte)0x01,(byte)0x01 - }; - } -} - -/** - * Addifional class to verify TrustManagerFactory constructor - */ - -class myTrustManagerFactory extends TrustManagerFactory { - public myTrustManagerFactory(TrustManagerFactorySpi spi, Provider prov, - String alg) { - super(spi, prov, alg); - } -} - diff --git a/luni/src/test/java/tests/api/javax/net/ssl/TrustManagerFactory2Test.java b/luni/src/test/java/tests/api/javax/net/ssl/TrustManagerFactory2Test.java deleted file mode 100644 index 0c0760f..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/TrustManagerFactory2Test.java +++ /dev/null @@ -1,255 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.net.ssl; - -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.Security; - -import javax.net.ssl.ManagerFactoryParameters; -import javax.net.ssl.TrustManagerFactory; - -import org.apache.harmony.security.tests.support.SpiEngUtils; -import org.apache.harmony.xnet.tests.support.MyTrustManagerFactorySpi; -import junit.framework.TestCase; - -/** - * Tests for TrustManagerFactory class constructors and methods - * - */ -public class TrustManagerFactory2Test extends TestCase { - private static final String srvTrustManagerFactory = "TrustManagerFactory"; - private static final String defaultAlg = "TMF"; - private static final String TrustManagerFactoryProviderClass = "org.apache.harmony.xnet.tests.support.MyTrustManagerFactorySpi"; - - private static final String[] invalidValues = SpiEngUtils.invalidValues; - - private static final String[] validValues; - - static { - validValues = new String[4]; - validValues[0] = defaultAlg; - validValues[1] = defaultAlg.toLowerCase(); - validValues[2] = "Tmf"; - validValues[3] = "tMF"; - } - - Provider mProv; - - protected void setUp() throws Exception { - super.setUp(); - mProv = (new SpiEngUtils()).new MyProvider("MyTMFProvider", - "Provider for testing", srvTrustManagerFactory.concat(".") - .concat(defaultAlg), TrustManagerFactoryProviderClass); - Security.insertProviderAt(mProv, 1); - } - - /* - * @see TestCase#tearDown() - */ - protected void tearDown() throws Exception { - super.tearDown(); - Security.removeProvider(mProv.getName()); - } - - private void checkResult(TrustManagerFactory tmf) throws Exception { - KeyStore kStore = null; - ManagerFactoryParameters mfp = null; - - try { - tmf.init(kStore); - fail("KeyStoreException must be thrown"); - } catch (KeyStoreException e) { - } - try { - tmf.init(mfp); - fail("InvalidAlgorithmParameterException must be thrown"); - } catch (InvalidAlgorithmParameterException e) { - } - assertNull("getTrustManagers() should return null object", tmf - .getTrustManagers()); - - try { - kStore = KeyStore.getInstance(KeyStore.getDefaultType()); - kStore.load(null, null); - } catch (KeyStoreException e) { - fail("default keystore is not supported"); - return; - } - tmf.init(kStore); - mfp = (ManagerFactoryParameters) new MyTrustManagerFactorySpi.Parameters(null); - try { - tmf.init(mfp); - fail("RuntimeException must be thrown"); - } catch (RuntimeException e) { - assertTrue("Incorrect exception", e.getCause() instanceof KeyStoreException); - } - mfp = (ManagerFactoryParameters) new MyTrustManagerFactorySpi.Parameters(kStore); - tmf.init(mfp); - } - - /** - * Test for <code>getInstance(String algorithm)</code> method - * Assertions: - * throws NullPointerException when algorithm is null; - * throws NoSuchAlgorithmException when algorithm is not correct; - * returns TrustManagerFactory object - */ - public void test_getInstanceLjava_lang_String() throws Exception { - try { - TrustManagerFactory.getInstance(null); - fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null"); - } catch (NoSuchAlgorithmException e) { - } catch (NullPointerException e) { - } - for (int i = 0; i < invalidValues.length; i++) { - try { - TrustManagerFactory.getInstance(invalidValues[i]); - fail("NoSuchAlgorithmException must be thrown (algorithm: " - .concat(invalidValues[i]).concat(")")); - } catch (NoSuchAlgorithmException e) { - } - } - TrustManagerFactory tmf; - for (int i = 0; i < validValues.length; i++) { - tmf = TrustManagerFactory.getInstance(validValues[i]); - assertTrue("Not instanceof TrustManagerFactory object", - tmf instanceof TrustManagerFactory); - assertEquals("Incorrect algorithm", tmf.getAlgorithm(), - validValues[i]); - assertEquals("Incorrect provider", tmf.getProvider(), mProv); - checkResult(tmf); - } - } - - /** - * Test for <code>getInstance(String algorithm, String provider)</code> - * method - * Assertions: - * throws NullPointerException when algorithm is null; - * throws NoSuchAlgorithmException when algorithm is not correct; - * throws IllegalArgumentException when provider is null or empty; - * throws NoSuchProviderException when provider is available; - * returns TrustManagerFactory object - */ - public void test_getInstanceLjava_lang_StringLjava_lang_String() throws Exception { - try { - TrustManagerFactory.getInstance(null, mProv.getName()); - fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null"); - } catch (NoSuchAlgorithmException e) { - } catch (NullPointerException e) { - } - for (int i = 0; i < invalidValues.length; i++) { - try { - TrustManagerFactory.getInstance(invalidValues[i], mProv - .getName()); - fail("NoSuchAlgorithmException must be thrown (algorithm: " - .concat(invalidValues[i]).concat(")")); - } catch (NoSuchAlgorithmException e) { - } - } - String prov = null; - for (int i = 0; i < validValues.length; i++) { - try { - TrustManagerFactory.getInstance(validValues[i], prov); - fail("IllegalArgumentException must be thrown when provider is null (algorithm: " - .concat(invalidValues[i]).concat(")")); - } catch (IllegalArgumentException e) { - } - try { - TrustManagerFactory.getInstance(validValues[i], ""); - fail("IllegalArgumentException must be thrown when provider is empty (algorithm: " - .concat(invalidValues[i]).concat(")")); - } catch (IllegalArgumentException e) { - } - } - for (int i = 0; i < validValues.length; i++) { - for (int j = 1; j < invalidValues.length; j++) { - try { - TrustManagerFactory.getInstance(validValues[i], - invalidValues[j]); - fail("NoSuchProviderException must be thrown (algorithm: " - .concat(invalidValues[i]).concat(" provider: ") - .concat(invalidValues[j]).concat(")")); - } catch (NoSuchProviderException e) { - } - } - } - TrustManagerFactory tmf; - for (int i = 0; i < validValues.length; i++) { - tmf = TrustManagerFactory.getInstance(validValues[i], mProv - .getName()); - assertTrue("Not instanceof TrustManagerFactory object", - tmf instanceof TrustManagerFactory); - assertEquals("Incorrect algorithm", tmf.getAlgorithm(), - validValues[i]); - assertEquals("Incorrect provider", tmf.getProvider().getName(), - mProv.getName()); - checkResult(tmf); - } - } - - /** - * Test for <code>getInstance(String algorithm, Provider provider)</code> - * method - * Assertions: - * throws NullPointerException when algorithm is null; - * throws NoSuchAlgorithmException when algorithm is not correct; - * throws IllegalArgumentException when provider is null; - * returns TrustManagerFactory object - */ - public void testLjava_lang_StringLjava_security_Provider() throws Exception { - try { - TrustManagerFactory.getInstance(null, mProv); - fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null"); - } catch (NoSuchAlgorithmException e) { - } catch (NullPointerException e) { - } - for (int i = 0; i < invalidValues.length; i++) { - try { - TrustManagerFactory.getInstance(invalidValues[i], mProv); - fail("NoSuchAlgorithmException must be thrown (algorithm: " - .concat(invalidValues[i]).concat(")")); - } catch (NoSuchAlgorithmException e) { - } - } - Provider prov = null; - for (int i = 0; i < validValues.length; i++) { - try { - TrustManagerFactory.getInstance(validValues[i], prov); - fail("IllegalArgumentException must be thrown when provider is null (algorithm: " - .concat(invalidValues[i]).concat(")")); - } catch (IllegalArgumentException e) { - } - } - TrustManagerFactory tmf; - for (int i = 0; i < validValues.length; i++) { - tmf = TrustManagerFactory.getInstance(validValues[i], mProv); - assertTrue("Not instanceof TrustManagerFactory object", - tmf instanceof TrustManagerFactory); - assertEquals("Incorrect algorithm", tmf.getAlgorithm(), - validValues[i]); - assertEquals("Incorrect provider", tmf.getProvider(), mProv); - checkResult(tmf); - } - } -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/TrustManagerFactorySpiTest.java b/luni/src/test/java/tests/api/javax/net/ssl/TrustManagerFactorySpiTest.java deleted file mode 100644 index 7bdeb45..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/TrustManagerFactorySpiTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.javax.net.ssl; - -import java.security.AccessController; -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; - -import javax.net.ssl.ManagerFactoryParameters; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.TrustManagerFactorySpi; - -import junit.framework.TestCase; -import org.apache.harmony.xnet.tests.support.TrustManagerFactorySpiImpl; -import org.apache.harmony.xnet.tests.support.MyTrustManagerFactorySpi.Parameters; - -public class TrustManagerFactorySpiTest extends TestCase { - - private TrustManagerFactorySpiImpl factory = new TrustManagerFactorySpiImpl(); - /** - * javax.net.ssl.TrustManagerFactorySpi#TrustManagerFactorySpi() - */ - public void test_Constructor() { - try { - TrustManagerFactorySpiImpl tmf = new TrustManagerFactorySpiImpl(); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - /** - * @throws NoSuchAlgorithmException - * @throws KeyStoreException - * javax.net.ssl.TrustManagerFactorySpi#engineInit(KeyStore ks) - */ - public void test_engineInit_01() throws NoSuchAlgorithmException, - KeyStoreException { - factory.reset(); - Provider provider = new MyProvider(); - TrustManagerFactory tmf = TrustManagerFactory.getInstance("MyTMF", - provider); - KeyStore ks = null; - try { - ks = KeyStore.getInstance(KeyStore.getDefaultType()); - ks.load(null, null); - tmf.init(ks); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - assertTrue(factory.isEngineInitCalled()); - assertEquals(ks, factory.getKs()); - factory.reset(); - tmf.init((KeyStore) null); - assertTrue(factory.isEngineInitCalled()); - assertNull(factory.getKs()); - } - - /** - * @throws InvalidAlgorithmParameterException - * @throws NoSuchAlgorithmException - * javax.net.ssl.TrustManagerFactorySpi#engineInit(ManagerFactoryParameters spec) - */ - public void test_engineInit_02() throws InvalidAlgorithmParameterException, - NoSuchAlgorithmException { - factory.reset(); - Provider provider = new MyProvider(); - TrustManagerFactory tmf = TrustManagerFactory.getInstance("MyTMF", - provider); - Parameters pr = null; - try { - KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); - ks.load(null, null); - pr = new Parameters(ks); - tmf.init(pr); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - assertTrue(factory.isEngineInitCalled()); - assertEquals(pr, factory.getSpec()); - factory.reset(); - tmf.init((ManagerFactoryParameters) null); - assertTrue(factory.isEngineInitCalled()); - assertNull(factory.getSpec()); - } - - /** - * @throws NoSuchAlgorithmException - * javax.net.ssl.TrustManagerFactorySpi#engineGetTrustManagers() - */ - public void test_engineGetTrustManagers() throws NoSuchAlgorithmException { - factory.reset(); - Provider provider = new MyProvider(); - TrustManagerFactory tmf = TrustManagerFactory.getInstance("MyTMF", - provider); - TrustManager[] tm = tmf.getTrustManagers(); - assertTrue(factory.isEngineGetTrustManagersCalled()); - factory.reset(); - try { - KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); - ks.load(null, null); - tmf.init(ks); - tm = tmf.getTrustManagers(); - assertTrue(factory.isEngineGetTrustManagersCalled()); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } -} - -class MyProvider extends Provider { - - public MyProvider() { - super("MyProvider", 1.0, "My Test Provider"); - AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() { - public Void run() { - put("TrustManagerFactory.MyTMF", - "org.apache.harmony.xnet.tests.support.TrustManagerFactorySpiImpl"); - return null; - } - }); - } -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/X509ExtendedKeyManagerTest.java b/luni/src/test/java/tests/api/javax/net/ssl/X509ExtendedKeyManagerTest.java deleted file mode 100644 index 514fed8..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/X509ExtendedKeyManagerTest.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.net.ssl; - -import java.net.Socket; -import java.security.Principal; -import java.security.PrivateKey; -import java.security.cert.X509Certificate; - -import javax.net.ssl.X509ExtendedKeyManager; - -import junit.framework.TestCase; - -/** - * Tests for <code>X509ExtendedKeyManager</code> class constructors and methods. - * - */ -public class X509ExtendedKeyManagerTest extends TestCase { - - private class MockX509ExtendedKeyManager extends X509ExtendedKeyManager { - public MockX509ExtendedKeyManager() { - super(); - } - - /** - * @see javax.net.ssl.X509KeyManager#chooseClientAlias(java.lang.String[], java.security.Principal[], java.net.Socket) - */ - public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) { - // it is a fake - return null; - } - - /** - * @see javax.net.ssl.X509KeyManager#chooseServerAlias(java.lang.String, java.security.Principal[], java.net.Socket) - */ - public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) { - // it is a fake - return null; - } - - /** - * @see javax.net.ssl.X509KeyManager#getCertificateChain(java.lang.String) - */ - public X509Certificate[] getCertificateChain(String arg0) { - // it is a fake - return null; - } - - /** - * @see javax.net.ssl.X509KeyManager#getClientAliases(java.lang.String, java.security.Principal[]) - */ - public String[] getClientAliases(String arg0, Principal[] arg1) { - // it is a fake - return null; - } - - /** - * @see javax.net.ssl.X509KeyManager#getPrivateKey(java.lang.String) - */ - public PrivateKey getPrivateKey(String arg0) { - // it is a fake - return null; - } - - /** - * @see javax.net.ssl.X509KeyManager#getServerAliases(java.lang.String, java.security.Principal[]) - */ - public String[] getServerAliases(String arg0, Principal[] arg1) { - // it is a fake - return null; - } - } - - /** - * javax.net.ssl.X509ExtendedKeyManager#X509ExtendedKeyManager() - */ - public final void test_Constructor() { - try { - new MockX509ExtendedKeyManager(); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - /** - * javax.net.ssl.X509ExtendedKeyManager - * #chooseEngineClientAlias(java.lang.String[], - * java.security.Principal[], javax.net.ssl.SSLEngine) - */ - public final void test_chooseEngineClientAlias() { - X509ExtendedKeyManager km = new MyX509ExtendedKeyManager(); - if (km.chooseEngineClientAlias(null, null, null) != null) { - fail("non null result"); - } - } - - /** - * javax.net.ssl.X509ExtendedKeyManager - * #chooseEngineServerAlias(java.lang.String, - * java.security.Principal[], javax.net.ssl.SSLEngine) - */ - public final void test_chooseEngineServerAlias() { - X509ExtendedKeyManager km = new MyX509ExtendedKeyManager(); - if (km.chooseEngineServerAlias(null, null, null) != null) { - fail("non null result"); - } - } - -} - -class MyX509ExtendedKeyManager extends X509ExtendedKeyManager { - - /* - * @see javax.net.ssl.X509KeyManager#chooseClientAlias(java.lang.String[], - * java.security.Principal[], java.net.Socket) - */ - public String chooseClientAlias(String[] keyType, Principal[] issuers, - Socket socket) { - return null; - } - - /* - * @see javax.net.ssl.X509KeyManager#chooseServerAlias(java.lang.String, - * java.security.Principal[], java.net.Socket) - */ - public String chooseServerAlias(String keyType, Principal[] issuers, - Socket socket) { - return null; - } - - /* - * @see javax.net.ssl.X509KeyManager#getCertificateChain(java.lang.String) - */ - public X509Certificate[] getCertificateChain(String alias) { - return null; - } - - /* - * @see javax.net.ssl.X509KeyManager#getClientAliases(java.lang.String, - * java.security.Principal[]) - */ - public String[] getClientAliases(String keyType, Principal[] issuers) { - return null; - } - - /* - * @see javax.net.ssl.X509KeyManager#getServerAliases(java.lang.String, - * java.security.Principal[]) - */ - public String[] getServerAliases(String keyType, Principal[] issuers) { - return null; - } - - /* - * @see javax.net.ssl.X509KeyManager#getPrivateKey(java.lang.String) - */ - public PrivateKey getPrivateKey(String alias) { - return null; - } - -} diff --git a/luni/src/test/java/tests/api/javax/net/ssl/X509KeyManagerTest.java b/luni/src/test/java/tests/api/javax/net/ssl/X509KeyManagerTest.java deleted file mode 100644 index 4dddbc6..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/X509KeyManagerTest.java +++ /dev/null @@ -1,753 +0,0 @@ -package tests.api.javax.net.ssl; - -import java.io.ByteArrayInputStream; -import java.net.Socket; -import java.security.KeyFactory; -import java.security.KeyStore; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.security.spec.PKCS8EncodedKeySpec; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.X509KeyManager; -import junit.framework.TestCase; - -/** - * Tests for <code>X509KeyManager</code> class constructors and methods. - */ -public class X509KeyManagerTest extends TestCase { - - private X509KeyManager manager; - private KeyManagerFactory factory; - - private static final String CLIENT = "CLIENT"; - private static final String SERVER = "SERVER"; - private static final String TYPE_RSA = "RSA"; - private static final char[] PASSWORD = "1234".toCharArray(); - - private String keyType; - private KeyStore keyTest; - private X509Certificate[] cert; - private PrivateKey[] keys; - - - /* - Certificate: - Data: - Version: 3 (0x2) - Serial Number: 0 (0x0) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=AN, ST=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com - Validity - Not Before: Mar 20 17:00:06 2009 GMT - Not After : Mar 19 17:00:06 2012 GMT - Subject: C=AN, ST=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - RSA Public Key: (1024 bit) - Modulus (1024 bit): - 00:aa:42:40:ed:92:21:17:99:5f:0e:e4:42:b8:cb: - 66:3d:63:2a:16:34:3c:7b:d3:3e:1f:a8:3f:bd:9a: - eb:b3:24:6b:8c:e4:da:2f:31:bc:61:07:27:2e:28: - 71:77:58:ae:b4:89:7c:eb:b0:06:24:07:57:3c:54: - 71:db:71:41:05:ab:3d:9f:05:d2:ca:cb:1c:bf:9d: - 8a:21:96:8f:13:61:25:69:12:3b:77:bd:f7:34:b2: - 09:a9:e0:52:94:44:31:ce:db:3d:eb:64:f1:d6:ca: - c5:7d:2f:d6:6f:8d:e4:29:8b:06:98:8a:95:3d:7a: - 97:41:9a:f1:66:c5:09:82:0d - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - E7:9B:7D:90:29:EA:90:0B:7F:08:41:76:4E:41:23:E8:43:2C:A9:03 - X509v3 Authority Key Identifier: - keyid:E7:9B:7D:90:29:EA:90:0B:7F:08:41:76:4E:41:23:E8:43:2C:A9:03 - DirName:/C=AN/ST=Android/O=Android/OU=Android/CN=Android/emailAddress=android@android.com - serial:00 - - X509v3 Basic Constraints: - CA:TRUE - Signature Algorithm: sha1WithRSAEncryption - 14:98:30:29:42:ef:ab:e6:b8:25:4b:55:85:04:a5:c4:dd:1d: - 8b:6a:c1:6f:6c:1c:1d:c3:61:34:30:07:34:4d:6a:8b:55:6f: - 75:55:6e:15:58:c5:f8:af:e0:be:73:ba:d9:a5:85:d7:b5:1a: - 85:44:2b:88:fd:cc:cb:d1:ed:46:69:43:ff:59:ae:9b:5c:17: - 26:da:ee:c8:bf:67:55:01:a0:0e:10:b9:85:49:54:d9:79:1e: - 7b:2e:6f:65:4f:d9:10:2e:9d:b8:92:63:67:74:8b:22:0d:6d: - d3:5d:9e:29:63:f9:36:93:1b:a7:80:e2:b1:f1:bf:29:19:81: - 3d:07 - */ - String certificate = "-----BEGIN CERTIFICATE-----\n" - + "MIIDPzCCAqigAwIBAgIBADANBgkqhkiG9w0BAQUFADB5MQswCQYDVQQGEwJBTjEQ\n" - + "MA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5k\n" - + "cm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBh\n" - + "bmRyb2lkLmNvbTAeFw0wOTAzMjAxNzAwMDZaFw0xMjAzMTkxNzAwMDZaMHkxCzAJ\n" - + "BgNVBAYTAkFOMRAwDgYDVQQIEwdBbmRyb2lkMRAwDgYDVQQKEwdBbmRyb2lkMRAw\n" - + "DgYDVQQLEwdBbmRyb2lkMRAwDgYDVQQDEwdBbmRyb2lkMSIwIAYJKoZIhvcNAQkB\n" - + "FhNhbmRyb2lkQGFuZHJvaWQuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB\n" - + "gQCqQkDtkiEXmV8O5EK4y2Y9YyoWNDx70z4fqD+9muuzJGuM5NovMbxhBycuKHF3\n" - + "WK60iXzrsAYkB1c8VHHbcUEFqz2fBdLKyxy/nYohlo8TYSVpEjt3vfc0sgmp4FKU\n" - + "RDHO2z3rZPHWysV9L9ZvjeQpiwaYipU9epdBmvFmxQmCDQIDAQABo4HWMIHTMB0G\n" - + "A1UdDgQWBBTnm32QKeqQC38IQXZOQSPoQyypAzCBowYDVR0jBIGbMIGYgBTnm32Q\n" - + "KeqQC38IQXZOQSPoQyypA6F9pHsweTELMAkGA1UEBhMCQU4xEDAOBgNVBAgTB0Fu\n" - + "ZHJvaWQxEDAOBgNVBAoTB0FuZHJvaWQxEDAOBgNVBAsTB0FuZHJvaWQxEDAOBgNV\n" - + "BAMTB0FuZHJvaWQxIjAgBgkqhkiG9w0BCQEWE2FuZHJvaWRAYW5kcm9pZC5jb22C\n" - + "AQAwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOBgQAUmDApQu+r5rglS1WF\n" - + "BKXE3R2LasFvbBwdw2E0MAc0TWqLVW91VW4VWMX4r+C+c7rZpYXXtRqFRCuI/czL\n" - + "0e1GaUP/Wa6bXBcm2u7Iv2dVAaAOELmFSVTZeR57Lm9lT9kQLp24kmNndIsiDW3T\n" - + "XZ4pY/k2kxungOKx8b8pGYE9Bw==\n" - + "-----END CERTIFICATE-----"; - - ByteArrayInputStream certArray = new ByteArrayInputStream(certificate - .getBytes()); - - /* - * The key in DER format. - * Below is the same key in PEM format as reference - */ - byte[] keyBytes = new byte[] { - (byte)0x30, (byte)0x82, (byte)0x02, (byte)0x77, (byte)0x02, (byte)0x01, (byte)0x00, - (byte)0x30, (byte)0x0d, (byte)0x06, (byte)0x09, (byte)0x2a, (byte)0x86, (byte)0x48, - (byte)0x86, (byte)0xf7, (byte)0x0d, (byte)0x01, (byte)0x01, (byte)0x01, (byte)0x05, - (byte)0x00, (byte)0x04, (byte)0x82, (byte)0x02, (byte)0x61, (byte)0x30, (byte)0x82, - (byte)0x02, (byte)0x5d, (byte)0x02, (byte)0x01, (byte)0x00, (byte)0x02, (byte)0x81, - (byte)0x81, (byte)0x00, (byte)0xaa, (byte)0x42, (byte)0x40, (byte)0xed, (byte)0x92, - (byte)0x21, (byte)0x17, (byte)0x99, (byte)0x5f, (byte)0x0e, (byte)0xe4, (byte)0x42, - (byte)0xb8, (byte)0xcb, (byte)0x66, (byte)0x3d, (byte)0x63, (byte)0x2a, (byte)0x16, - (byte)0x34, (byte)0x3c, (byte)0x7b, (byte)0xd3, (byte)0x3e, (byte)0x1f, (byte)0xa8, - (byte)0x3f, (byte)0xbd, (byte)0x9a, (byte)0xeb, (byte)0xb3, (byte)0x24, (byte)0x6b, - (byte)0x8c, (byte)0xe4, (byte)0xda, (byte)0x2f, (byte)0x31, (byte)0xbc, (byte)0x61, - (byte)0x07, (byte)0x27, (byte)0x2e, (byte)0x28, (byte)0x71, (byte)0x77, (byte)0x58, - (byte)0xae, (byte)0xb4, (byte)0x89, (byte)0x7c, (byte)0xeb, (byte)0xb0, (byte)0x06, - (byte)0x24, (byte)0x07, (byte)0x57, (byte)0x3c, (byte)0x54, (byte)0x71, (byte)0xdb, - (byte)0x71, (byte)0x41, (byte)0x05, (byte)0xab, (byte)0x3d, (byte)0x9f, (byte)0x05, - (byte)0xd2, (byte)0xca, (byte)0xcb, (byte)0x1c, (byte)0xbf, (byte)0x9d, (byte)0x8a, - (byte)0x21, (byte)0x96, (byte)0x8f, (byte)0x13, (byte)0x61, (byte)0x25, (byte)0x69, - (byte)0x12, (byte)0x3b, (byte)0x77, (byte)0xbd, (byte)0xf7, (byte)0x34, (byte)0xb2, - (byte)0x09, (byte)0xa9, (byte)0xe0, (byte)0x52, (byte)0x94, (byte)0x44, (byte)0x31, - (byte)0xce, (byte)0xdb, (byte)0x3d, (byte)0xeb, (byte)0x64, (byte)0xf1, (byte)0xd6, - (byte)0xca, (byte)0xc5, (byte)0x7d, (byte)0x2f, (byte)0xd6, (byte)0x6f, (byte)0x8d, - (byte)0xe4, (byte)0x29, (byte)0x8b, (byte)0x06, (byte)0x98, (byte)0x8a, (byte)0x95, - (byte)0x3d, (byte)0x7a, (byte)0x97, (byte)0x41, (byte)0x9a, (byte)0xf1, (byte)0x66, - (byte)0xc5, (byte)0x09, (byte)0x82, (byte)0x0d, (byte)0x02, (byte)0x03, (byte)0x01, - (byte)0x00, (byte)0x01, (byte)0x02, (byte)0x81, (byte)0x80, (byte)0x34, (byte)0x91, - (byte)0x8e, (byte)0x50, (byte)0x8b, (byte)0xfc, (byte)0xf1, (byte)0xb7, (byte)0x66, - (byte)0x35, (byte)0x47, (byte)0xdf, (byte)0x1e, (byte)0x05, (byte)0x97, (byte)0x44, - (byte)0xbe, (byte)0xf8, (byte)0x80, (byte)0xb0, (byte)0x92, (byte)0x38, (byte)0x3d, - (byte)0x4a, (byte)0x02, (byte)0x26, (byte)0x45, (byte)0xbf, (byte)0xfa, (byte)0x34, - (byte)0x6a, (byte)0x34, (byte)0x85, (byte)0x8c, (byte)0x94, (byte)0x20, (byte)0x95, - (byte)0xcf, (byte)0xca, (byte)0x75, (byte)0x3e, (byte)0xeb, (byte)0x27, (byte)0x02, - (byte)0x4f, (byte)0xbe, (byte)0x64, (byte)0xc0, (byte)0x54, (byte)0x77, (byte)0xda, - (byte)0xfd, (byte)0x3e, (byte)0x75, (byte)0x36, (byte)0xec, (byte)0x99, (byte)0x4f, - (byte)0xc4, (byte)0x56, (byte)0xff, (byte)0x45, (byte)0x61, (byte)0xa8, (byte)0xa8, - (byte)0x41, (byte)0xe4, (byte)0x42, (byte)0x71, (byte)0x7a, (byte)0x8c, (byte)0x84, - (byte)0xc2, (byte)0x02, (byte)0x40, (byte)0x0b, (byte)0x3d, (byte)0x42, (byte)0xe0, - (byte)0x8b, (byte)0x22, (byte)0xf7, (byte)0x4c, (byte)0xa3, (byte)0xbb, (byte)0xd8, - (byte)0x8f, (byte)0x45, (byte)0xa2, (byte)0x55, (byte)0xc7, (byte)0xd0, (byte)0x6a, - (byte)0x25, (byte)0xbf, (byte)0xda, (byte)0x54, (byte)0x57, (byte)0x14, (byte)0x91, - (byte)0x0c, (byte)0x09, (byte)0x0b, (byte)0x9a, (byte)0x50, (byte)0xca, (byte)0xe6, - (byte)0x9e, (byte)0x28, (byte)0xc3, (byte)0x78, (byte)0x39, (byte)0x10, (byte)0x06, - (byte)0x02, (byte)0x96, (byte)0x10, (byte)0x1a, (byte)0xd2, (byte)0x4b, (byte)0x7b, - (byte)0x6c, (byte)0x72, (byte)0x9e, (byte)0x1e, (byte)0xac, (byte)0xd2, (byte)0xc1, - (byte)0x02, (byte)0x41, (byte)0x00, (byte)0xde, (byte)0x27, (byte)0xbd, (byte)0x43, - (byte)0xa4, (byte)0xbd, (byte)0x95, (byte)0x14, (byte)0x2e, (byte)0x1c, (byte)0xa0, - (byte)0x74, (byte)0xa5, (byte)0x3e, (byte)0xfa, (byte)0xf9, (byte)0x15, (byte)0xb2, - (byte)0x29, (byte)0x6a, (byte)0x2a, (byte)0x42, (byte)0x94, (byte)0x5a, (byte)0xf2, - (byte)0x81, (byte)0xf3, (byte)0xe1, (byte)0x76, (byte)0x49, (byte)0x11, (byte)0x9d, - (byte)0x18, (byte)0xc5, (byte)0xeb, (byte)0xb6, (byte)0xbc, (byte)0x81, (byte)0x3a, - (byte)0x14, (byte)0x9c, (byte)0x41, (byte)0x01, (byte)0x58, (byte)0x56, (byte)0xa9, - (byte)0x9b, (byte)0x73, (byte)0x2f, (byte)0xd9, (byte)0xa8, (byte)0x8e, (byte)0xc4, - (byte)0x48, (byte)0x69, (byte)0x35, (byte)0xe6, (byte)0xf4, (byte)0x73, (byte)0x2f, - (byte)0xf9, (byte)0x12, (byte)0x12, (byte)0x71, (byte)0x02, (byte)0x41, (byte)0x00, - (byte)0xc4, (byte)0x32, (byte)0x81, (byte)0x5d, (byte)0x19, (byte)0x54, (byte)0x2c, - (byte)0x29, (byte)0x5a, (byte)0x9f, (byte)0x36, (byte)0x4c, (byte)0x6f, (byte)0x2d, - (byte)0xfd, (byte)0x62, (byte)0x0e, (byte)0xe6, (byte)0x37, (byte)0xc2, (byte)0xf6, - (byte)0x69, (byte)0x64, (byte)0xf9, (byte)0x3a, (byte)0xcc, (byte)0xb2, (byte)0x63, - (byte)0x2f, (byte)0xa9, (byte)0xfe, (byte)0x7e, (byte)0x8b, (byte)0x2d, (byte)0x69, - (byte)0x13, (byte)0xe5, (byte)0x61, (byte)0x58, (byte)0xb7, (byte)0xfa, (byte)0x55, - (byte)0x74, (byte)0x2c, (byte)0xe8, (byte)0xa1, (byte)0xac, (byte)0xc3, (byte)0xdd, - (byte)0x5b, (byte)0x62, (byte)0xae, (byte)0x0a, (byte)0x27, (byte)0xce, (byte)0xb0, - (byte)0xf2, (byte)0x81, (byte)0x5f, (byte)0x9a, (byte)0x6f, (byte)0x5f, (byte)0x3f, - (byte)0x5d, (byte)0x02, (byte)0x41, (byte)0x00, (byte)0x92, (byte)0x42, (byte)0xff, - (byte)0xac, (byte)0xe5, (byte)0x6d, (byte)0x9c, (byte)0x15, (byte)0x29, (byte)0x36, - (byte)0xd7, (byte)0xbd, (byte)0x74, (byte)0x7e, (byte)0x3e, (byte)0xa6, (byte)0x77, - (byte)0xce, (byte)0x50, (byte)0xce, (byte)0x00, (byte)0xfc, (byte)0xcc, (byte)0xc8, - (byte)0x04, (byte)0x19, (byte)0xe3, (byte)0x03, (byte)0x71, (byte)0xe9, (byte)0x31, - (byte)0x9b, (byte)0x88, (byte)0x8f, (byte)0xe6, (byte)0x5c, (byte)0xed, (byte)0x46, - (byte)0xf7, (byte)0x82, (byte)0x52, (byte)0x4d, (byte)0xca, (byte)0x20, (byte)0xeb, - (byte)0x0d, (byte)0xc7, (byte)0xb6, (byte)0xd2, (byte)0xae, (byte)0x2e, (byte)0xf7, - (byte)0xaf, (byte)0xeb, (byte)0x2c, (byte)0xb9, (byte)0xbc, (byte)0x50, (byte)0xfc, - (byte)0xf5, (byte)0x7c, (byte)0xba, (byte)0x95, (byte)0x41, (byte)0x02, (byte)0x40, - (byte)0x54, (byte)0xf8, (byte)0x46, (byte)0x9c, (byte)0x6a, (byte)0x5e, (byte)0xd0, - (byte)0xed, (byte)0x6c, (byte)0x08, (byte)0xed, (byte)0xfc, (byte)0x36, (byte)0x5e, - (byte)0x65, (byte)0x91, (byte)0x75, (byte)0x40, (byte)0x71, (byte)0x3f, (byte)0xe7, - (byte)0x76, (byte)0x07, (byte)0xbc, (byte)0x04, (byte)0xa2, (byte)0x28, (byte)0x53, - (byte)0xda, (byte)0x8d, (byte)0xb5, (byte)0xe1, (byte)0x5a, (byte)0x27, (byte)0x65, - (byte)0x8d, (byte)0xaf, (byte)0x56, (byte)0xf4, (byte)0x94, (byte)0x61, (byte)0x3f, - (byte)0x67, (byte)0x1c, (byte)0x17, (byte)0xf8, (byte)0x05, (byte)0x19, (byte)0xa2, - (byte)0xa1, (byte)0x74, (byte)0x60, (byte)0x49, (byte)0x97, (byte)0xa9, (byte)0xe5, - (byte)0x6a, (byte)0x71, (byte)0x6b, (byte)0x55, (byte)0x38, (byte)0x0c, (byte)0xb9, - (byte)0x25, (byte)0x02, (byte)0x41, (byte)0x00, (byte)0xae, (byte)0xf2, (byte)0xa8, - (byte)0x6d, (byte)0x1d, (byte)0x35, (byte)0x38, (byte)0x73, (byte)0x98, (byte)0x15, - (byte)0xc7, (byte)0x15, (byte)0x02, (byte)0x2f, (byte)0x29, (byte)0x5d, (byte)0x18, - (byte)0x4b, (byte)0x7d, (byte)0xb2, (byte)0x59, (byte)0xbe, (byte)0x5a, (byte)0xc7, - (byte)0x72, (byte)0xd0, (byte)0x80, (byte)0xd8, (byte)0x77, (byte)0xa1, (byte)0x7f, - (byte)0xb2, (byte)0x35, (byte)0x0d, (byte)0x78, (byte)0x92, (byte)0x91, (byte)0x35, - (byte)0x47, (byte)0xeb, (byte)0x4b, (byte)0x00, (byte)0x59, (byte)0xb4, (byte)0xc4, - (byte)0x2c, (byte)0x29, (byte)0xe7, (byte)0x39, (byte)0x9d, (byte)0x48, (byte)0x8b, - (byte)0x4f, (byte)0x46, (byte)0xe6, (byte)0xce, (byte)0xd3, (byte)0x6c, (byte)0x84, - (byte)0x9b, (byte)0xd2, (byte)0x10, (byte)0xb0, (byte)0xe1 - }; - - /* - * The same key in PEM format. - * The DER version of this key was created using - * - * openssl pkcs8 -topk8 -nocrypt -in key1.pem - * -inform PEM -out key1.der -outform DER - * - * -----BEGIN RSA PRIVATE KEY----- - * Proc-Type: 4,ENCRYPTED - * DEK-Info: DES-EDE3-CBC,69E26FCC3A7F136E - * - * YKiLXOwf2teog4IoOvbbROy9vqp0EMt1KF9eNKeKFCWGCS4RFATaAGjKrdA26bOV - * MBdyB4V7qaxLC8/UwLlzFLpprouIfGqrEoR/NT0eKQ+4Pl25GlMvlPaR0pATBLZ2 - * OEaB3zcNygOQ02Jdrmw2+CS9qVtGGXjn6Qp6TVFm6edNCoOVZODLP9kkzPLn8Mkm - * /isgsprwMELuth8Y5BC0brI5XYdMqZFI5dLz4wzVH81wBYbRmJqR7yOE1pzAJS9I - * gJ5YvcP7pSmoA2SHVN4v4qolM+GAM9YIp2bwEyWFRjbriNlF1yM+HflGMEZ1HNpZ - * FSFFA3G8EIH9ogbZ3j+7EujrndJC7GIibwiu5rd3eIHtcwrWprp+wEoPc/vM8OpR - * so9ms7iQYV6faYCWK4yeCfErYw7t+AhGqfLiqHO6bO2XAYJcD28RYV9gXmugZOhT - * 9471MOw94HWF5tBVjgIkyNBcbRyMF9iyQKafbkHYpmxaB4s2EqQr1SNZl3SLEwhX - * MEGy3/tyveuMLAvdTlSDZbt6memWoXXEX4Ep/q6r0ErCTY31awdP/XaJcJBGb9ni - * Iai8DICaG1v4bUuBVgaiacZlgw1O4Hhj8D2DWfVZsgpx5y8tBRM2lGWvyzEi5n2F - * PiR2UlT0DjCD1ObjCpWJ5insX/w8dXSHGZLLb9ccGRUrw/+5Bptn+AoEfdP+8S3j - * UdMdxl6qt2gneCYu1Lr3cQ+qKPqikQty2UQ6Yp8dJkheLJ2Tr+rnaytOCp2dAT9K - * KXTimIcXV+ftvUMbDPXYu4LJBldr2VokD+k3QbHDgFnfHIiNkwiPzA== - * -----END RSA PRIVATE KEY----- - */ - - /* - Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=AN, ST=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com - Validity - Not Before: Mar 20 17:00:40 2009 GMT - Not After : Mar 20 17:00:40 2010 GMT - Subject: C=AN, ST=Android, L=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - RSA Public Key: (1024 bit) - Modulus (1024 bit): - 00:d0:44:5a:c4:76:ef:ae:ff:99:5b:c3:37:c1:09: - 33:c1:97:e5:64:7a:a9:7e:98:4b:3a:a3:33:d0:5c: - c7:56:ac:d8:42:e8:4a:ac:9c:d9:8f:89:84:c8:46: - 95:ce:22:f7:6a:09:de:91:47:9c:38:23:a5:4a:fc: - 08:af:5a:b4:6e:39:8e:e9:f5:0e:46:00:69:e1:e5: - cc:4c:81:b6:82:7b:56:fb:f4:dc:04:ff:61:e2:7e: - 5f:e2:f9:97:53:93:d4:69:9b:ba:79:20:cd:1e:3e: - d5:9a:44:95:7c:cf:c1:51:f2:22:fc:ec:cc:66:18: - 74:60:2a:a2:be:06:c2:9e:8d - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: - CA:FALSE - Netscape Comment: - OpenSSL Generated Certificate - X509v3 Subject Key Identifier: - 95:3E:C3:46:69:52:78:08:05:46:B9:00:69:E5:E7:A7:99:E3:C4:67 - X509v3 Authority Key Identifier: - keyid:E7:9B:7D:90:29:EA:90:0B:7F:08:41:76:4E:41:23:E8:43:2C:A9:03 - - Signature Algorithm: sha1WithRSAEncryption - a3:5b:30:f5:28:3f:87:f6:1b:36:6a:22:6d:66:48:fa:cb:ee: - 4c:04:cf:11:14:e2:1f:b5:68:0c:e7:61:0e:bc:d3:69:19:02: - 8b:d5:d3:05:4a:c8:29:e8:e3:d0:e9:32:ad:6c:7d:9c:c4:46: - 6c:f9:66:e6:64:60:47:6b:ef:8e:c8:1c:67:5a:5a:cf:73:a3: - 7e:9d:6e:89:0c:67:99:17:3d:b2:b8:8e:41:95:9c:84:95:bf: - 57:95:24:22:8f:19:12:c1:fd:23:45:75:7f:4f:61:06:e3:9f: - 05:dc:e7:29:9a:6b:17:e1:e1:37:d5:8b:ba:b4:d0:8a:3c:dd: - 3f:6a - */ - String certificate2 = "-----BEGIN CERTIFICATE-----\n" - + "MIIC9jCCAl+gAwIBAgIBATANBgkqhkiG9w0BAQUFADB5MQswCQYDVQQGEwJBTjEQ\n" - + "MA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5k\n" - + "cm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBh\n" - + "bmRyb2lkLmNvbTAeFw0wOTAzMjAxNzAwNDBaFw0xMDAzMjAxNzAwNDBaMIGLMQsw\n" - + "CQYDVQQGEwJBTjEQMA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEBxMHQW5kcm9pZDEQ\n" - + "MA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5k\n" - + "cm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTCBnzANBgkq\n" - + "hkiG9w0BAQEFAAOBjQAwgYkCgYEA0ERaxHbvrv+ZW8M3wQkzwZflZHqpfphLOqMz\n" - + "0FzHVqzYQuhKrJzZj4mEyEaVziL3agnekUecOCOlSvwIr1q0bjmO6fUORgBp4eXM\n" - + "TIG2gntW+/TcBP9h4n5f4vmXU5PUaZu6eSDNHj7VmkSVfM/BUfIi/OzMZhh0YCqi\n" - + "vgbCno0CAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNT\n" - + "TCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFJU+w0ZpUngIBUa5AGnl\n" - + "56eZ48RnMB8GA1UdIwQYMBaAFOebfZAp6pALfwhBdk5BI+hDLKkDMA0GCSqGSIb3\n" - + "DQEBBQUAA4GBAKNbMPUoP4f2GzZqIm1mSPrL7kwEzxEU4h+1aAznYQ6802kZAovV\n" - + "0wVKyCno49DpMq1sfZzERmz5ZuZkYEdr747IHGdaWs9zo36dbokMZ5kXPbK4jkGV\n" - + "nISVv1eVJCKPGRLB/SNFdX9PYQbjnwXc5ymaaxfh4TfVi7q00Io83T9q\n\n" - + "-----END CERTIFICATE-----"; - - ByteArrayInputStream certArray2 = new ByteArrayInputStream(certificate2 - .getBytes()); - - /* - * The key in DER format. - * Below is the same key in PEM format as reference - */ - byte[] key2Bytes = new byte[] { - (byte)0x30, (byte)0x82, (byte)0x02, (byte)0x75, (byte)0x02, (byte)0x01, (byte)0x00, - (byte)0x30, (byte)0x0d, (byte)0x06, (byte)0x09, (byte)0x2a, (byte)0x86, (byte)0x48, - (byte)0x86, (byte)0xf7, (byte)0x0d, (byte)0x01, (byte)0x01, (byte)0x01, (byte)0x05, - (byte)0x00, (byte)0x04, (byte)0x82, (byte)0x02, (byte)0x5f, (byte)0x30, (byte)0x82, - (byte)0x02, (byte)0x5b, (byte)0x02, (byte)0x01, (byte)0x00, (byte)0x02, (byte)0x81, - (byte)0x81, (byte)0x00, (byte)0xd0, (byte)0x44, (byte)0x5a, (byte)0xc4, (byte)0x76, - (byte)0xef, (byte)0xae, (byte)0xff, (byte)0x99, (byte)0x5b, (byte)0xc3, (byte)0x37, - (byte)0xc1, (byte)0x09, (byte)0x33, (byte)0xc1, (byte)0x97, (byte)0xe5, (byte)0x64, - (byte)0x7a, (byte)0xa9, (byte)0x7e, (byte)0x98, (byte)0x4b, (byte)0x3a, (byte)0xa3, - (byte)0x33, (byte)0xd0, (byte)0x5c, (byte)0xc7, (byte)0x56, (byte)0xac, (byte)0xd8, - (byte)0x42, (byte)0xe8, (byte)0x4a, (byte)0xac, (byte)0x9c, (byte)0xd9, (byte)0x8f, - (byte)0x89, (byte)0x84, (byte)0xc8, (byte)0x46, (byte)0x95, (byte)0xce, (byte)0x22, - (byte)0xf7, (byte)0x6a, (byte)0x09, (byte)0xde, (byte)0x91, (byte)0x47, (byte)0x9c, - (byte)0x38, (byte)0x23, (byte)0xa5, (byte)0x4a, (byte)0xfc, (byte)0x08, (byte)0xaf, - (byte)0x5a, (byte)0xb4, (byte)0x6e, (byte)0x39, (byte)0x8e, (byte)0xe9, (byte)0xf5, - (byte)0x0e, (byte)0x46, (byte)0x00, (byte)0x69, (byte)0xe1, (byte)0xe5, (byte)0xcc, - (byte)0x4c, (byte)0x81, (byte)0xb6, (byte)0x82, (byte)0x7b, (byte)0x56, (byte)0xfb, - (byte)0xf4, (byte)0xdc, (byte)0x04, (byte)0xff, (byte)0x61, (byte)0xe2, (byte)0x7e, - (byte)0x5f, (byte)0xe2, (byte)0xf9, (byte)0x97, (byte)0x53, (byte)0x93, (byte)0xd4, - (byte)0x69, (byte)0x9b, (byte)0xba, (byte)0x79, (byte)0x20, (byte)0xcd, (byte)0x1e, - (byte)0x3e, (byte)0xd5, (byte)0x9a, (byte)0x44, (byte)0x95, (byte)0x7c, (byte)0xcf, - (byte)0xc1, (byte)0x51, (byte)0xf2, (byte)0x22, (byte)0xfc, (byte)0xec, (byte)0xcc, - (byte)0x66, (byte)0x18, (byte)0x74, (byte)0x60, (byte)0x2a, (byte)0xa2, (byte)0xbe, - (byte)0x06, (byte)0xc2, (byte)0x9e, (byte)0x8d, (byte)0x02, (byte)0x03, (byte)0x01, - (byte)0x00, (byte)0x01, (byte)0x02, (byte)0x81, (byte)0x80, (byte)0x06, (byte)0x41, - (byte)0xd7, (byte)0x7c, (byte)0x49, (byte)0x9a, (byte)0x7f, (byte)0xe6, (byte)0x7c, - (byte)0x04, (byte)0x0e, (byte)0xc4, (byte)0x71, (byte)0x0f, (byte)0x46, (byte)0xb7, - (byte)0xcd, (byte)0x49, (byte)0x7e, (byte)0x10, (byte)0x55, (byte)0x61, (byte)0x51, - (byte)0x50, (byte)0x09, (byte)0x4d, (byte)0xf7, (byte)0xf3, (byte)0x8d, (byte)0xa6, - (byte)0x0b, (byte)0x8b, (byte)0x9b, (byte)0xdf, (byte)0xbe, (byte)0xbc, (byte)0xe7, - (byte)0x9c, (byte)0xba, (byte)0xc8, (byte)0x9e, (byte)0x38, (byte)0x18, (byte)0x10, - (byte)0x4e, (byte)0xd5, (byte)0xe7, (byte)0xa5, (byte)0x09, (byte)0x51, (byte)0x8c, - (byte)0x97, (byte)0x4e, (byte)0xd0, (byte)0x79, (byte)0xbb, (byte)0x50, (byte)0x6f, - (byte)0x05, (byte)0x4d, (byte)0x79, (byte)0x7f, (byte)0x3f, (byte)0x26, (byte)0x76, - (byte)0xc1, (byte)0xcc, (byte)0x40, (byte)0x0f, (byte)0xde, (byte)0x42, (byte)0x5d, - (byte)0xc1, (byte)0x5f, (byte)0x70, (byte)0x46, (byte)0x70, (byte)0x8d, (byte)0xff, - (byte)0x26, (byte)0x35, (byte)0x75, (byte)0x9a, (byte)0x97, (byte)0xd2, (byte)0x74, - (byte)0x53, (byte)0x11, (byte)0x2b, (byte)0xc1, (byte)0x76, (byte)0x9c, (byte)0x9f, - (byte)0x93, (byte)0xaa, (byte)0xa8, (byte)0x41, (byte)0x23, (byte)0x9a, (byte)0x04, - (byte)0x11, (byte)0x6e, (byte)0x56, (byte)0xea, (byte)0xf5, (byte)0xd6, (byte)0x1d, - (byte)0x49, (byte)0x2a, (byte)0x83, (byte)0x49, (byte)0x7d, (byte)0xb7, (byte)0xd1, - (byte)0xe6, (byte)0x8d, (byte)0x93, (byte)0x1a, (byte)0x81, (byte)0x8e, (byte)0xc2, - (byte)0xb9, (byte)0xbf, (byte)0xfd, (byte)0x00, (byte)0xe2, (byte)0xb5, (byte)0x01, - (byte)0x02, (byte)0x41, (byte)0x00, (byte)0xea, (byte)0xce, (byte)0xc6, (byte)0x11, - (byte)0x1e, (byte)0xf6, (byte)0xcf, (byte)0x3a, (byte)0x8c, (byte)0xe7, (byte)0x80, - (byte)0x16, (byte)0x8f, (byte)0x1d, (byte)0xeb, (byte)0xa2, (byte)0xd2, (byte)0x23, - (byte)0x9e, (byte)0xf9, (byte)0xf1, (byte)0x14, (byte)0x16, (byte)0xc8, (byte)0x87, - (byte)0xf2, (byte)0x17, (byte)0xdf, (byte)0xc6, (byte)0xe4, (byte)0x1c, (byte)0x74, - (byte)0x74, (byte)0xb0, (byte)0xbb, (byte)0x40, (byte)0xeb, (byte)0xa6, (byte)0xb2, - (byte)0x5b, (byte)0x6d, (byte)0xf5, (byte)0x9a, (byte)0x85, (byte)0xf1, (byte)0x73, - (byte)0x84, (byte)0xec, (byte)0xdb, (byte)0x9b, (byte)0xf9, (byte)0xf8, (byte)0x3d, - (byte)0xba, (byte)0xeb, (byte)0xd7, (byte)0x6c, (byte)0x45, (byte)0x7b, (byte)0xca, - (byte)0x12, (byte)0x67, (byte)0x5f, (byte)0xcd, (byte)0x02, (byte)0x41, (byte)0x00, - (byte)0xe3, (byte)0x10, (byte)0x5b, (byte)0xd0, (byte)0xad, (byte)0x59, (byte)0x90, - (byte)0x18, (byte)0x17, (byte)0xdc, (byte)0x68, (byte)0xd4, (byte)0x75, (byte)0x55, - (byte)0xab, (byte)0x7d, (byte)0xd1, (byte)0xb5, (byte)0x5a, (byte)0xc4, (byte)0xb0, - (byte)0x2d, (byte)0xa9, (byte)0xd1, (byte)0x6f, (byte)0xe9, (byte)0x21, (byte)0x4a, - (byte)0x27, (byte)0xc4, (byte)0x98, (byte)0x89, (byte)0xfa, (byte)0x65, (byte)0xb6, - (byte)0x10, (byte)0x5d, (byte)0x66, (byte)0xdd, (byte)0x17, (byte)0xb3, (byte)0xf3, - (byte)0xd3, (byte)0xe3, (byte)0xa0, (byte)0x1a, (byte)0x93, (byte)0xe4, (byte)0xfb, - (byte)0x88, (byte)0xa7, (byte)0x3b, (byte)0x97, (byte)0x1b, (byte)0xf1, (byte)0x08, - (byte)0x0c, (byte)0x66, (byte)0xd0, (byte)0x86, (byte)0x5e, (byte)0x39, (byte)0xf9, - (byte)0xc1, (byte)0x02, (byte)0x40, (byte)0x24, (byte)0x7c, (byte)0xcd, (byte)0x3a, - (byte)0x8b, (byte)0xdd, (byte)0x3e, (byte)0x86, (byte)0x92, (byte)0xae, (byte)0xc6, - (byte)0xb0, (byte)0xba, (byte)0xbc, (byte)0xa3, (byte)0x89, (byte)0x41, (byte)0xae, - (byte)0x57, (byte)0x5d, (byte)0xef, (byte)0xa0, (byte)0x77, (byte)0x89, (byte)0xe1, - (byte)0xd6, (byte)0x34, (byte)0xef, (byte)0x89, (byte)0x30, (byte)0x99, (byte)0x5b, - (byte)0x5f, (byte)0x66, (byte)0xb7, (byte)0x32, (byte)0x77, (byte)0x6c, (byte)0x07, - (byte)0xfb, (byte)0x3d, (byte)0x33, (byte)0x15, (byte)0x38, (byte)0x0b, (byte)0x35, - (byte)0x30, (byte)0x4a, (byte)0xbe, (byte)0x35, (byte)0x96, (byte)0xba, (byte)0x84, - (byte)0x9d, (byte)0x2f, (byte)0x58, (byte)0xe2, (byte)0x72, (byte)0x49, (byte)0xb2, - (byte)0x34, (byte)0xf9, (byte)0xeb, (byte)0x61, (byte)0x02, (byte)0x40, (byte)0x2a, - (byte)0xd4, (byte)0x89, (byte)0x1d, (byte)0x21, (byte)0xb5, (byte)0xc5, (byte)0x32, - (byte)0x66, (byte)0x3d, (byte)0xd3, (byte)0x20, (byte)0x50, (byte)0x49, (byte)0xaa, - (byte)0xa1, (byte)0x7f, (byte)0x0f, (byte)0x20, (byte)0x61, (byte)0xfd, (byte)0x81, - (byte)0x7f, (byte)0x88, (byte)0xdb, (byte)0xfd, (byte)0x33, (byte)0xa4, (byte)0x53, - (byte)0x40, (byte)0x08, (byte)0x2d, (byte)0xee, (byte)0xa7, (byte)0x84, (byte)0xe2, - (byte)0x2d, (byte)0x5c, (byte)0x1b, (byte)0xd4, (byte)0x3e, (byte)0xc3, (byte)0x7d, - (byte)0x72, (byte)0x70, (byte)0x5e, (byte)0xd3, (byte)0x0a, (byte)0xdc, (byte)0x4f, - (byte)0x78, (byte)0x8c, (byte)0x0b, (byte)0x02, (byte)0xe0, (byte)0x42, (byte)0x4e, - (byte)0x64, (byte)0x8e, (byte)0x6c, (byte)0xea, (byte)0x15, (byte)0x31, (byte)0x81, - (byte)0x02, (byte)0x40, (byte)0x57, (byte)0x72, (byte)0xb9, (byte)0x78, (byte)0xc0, - (byte)0x1f, (byte)0x5b, (byte)0x1d, (byte)0xb2, (byte)0xcf, (byte)0x94, (byte)0x42, - (byte)0xed, (byte)0xbd, (byte)0xe7, (byte)0xaa, (byte)0x14, (byte)0x56, (byte)0xd0, - (byte)0x94, (byte)0x25, (byte)0x30, (byte)0x87, (byte)0x35, (byte)0x82, (byte)0xa0, - (byte)0x42, (byte)0xb5, (byte)0x7f, (byte)0x66, (byte)0x77, (byte)0xb0, (byte)0x13, - (byte)0xbe, (byte)0x57, (byte)0x06, (byte)0x7e, (byte)0x50, (byte)0x67, (byte)0x13, - (byte)0xa7, (byte)0x09, (byte)0xac, (byte)0xd6, (byte)0xbf, (byte)0x22, (byte)0x74, - (byte)0x6b, (byte)0x37, (byte)0x92, (byte)0x2b, (byte)0x91, (byte)0xbd, (byte)0x0a, - (byte)0xd8, (byte)0x0f, (byte)0x8d, (byte)0x86, (byte)0x4b, (byte)0x20, (byte)0x5e, - (byte)0x50, (byte)0x60, (byte)0x80 - }; - - /* - * The same key in PEM format. - * The DER version of this key was created using - * - * openssl pkcs8 -topk8 -nocrypt -in key1.pem - * -inform PEM -out key1.der -outform DER - * - * -----BEGIN RSA PRIVATE KEY----- - * Proc-Type: 4,ENCRYPTED - * DEK-Info: DES-EDE3-CBC,370723FFDC1B1CFA - * - * KJ20ODBEQujoOpnzNfHNoo5DF/qENhw9IaApChGMj+WhqYuFfKfPQKuRli8sJSEk - * uoPmEqjJndHz5M5bI7wVxiafv/Up4+SaNKhn/vu6xjx/senJMX8HMUchqfvn0eCd - * 31NHQeNbQ67O73xGIdltLzwTRsavTu/hwhnnJxiXzXnYtI5HTZUaRbVJQNpdlkNW - * H91u70lwlT8W2MATBhl3R3wIbRHQG1I0RQX12O04gMfK1PBl9d/tnFOi4ESfth1W - * e06XV0U12g06V5/UUuicJANvgyf0Pix0xxPr2tqibWeGpFwCvJpNHl4L3tUocydF - * HYoUKx/r3VSmesnZ1zUMsuO2zXOuLLcwCSFN+73GBLWocCxBvag6HFvCemy5Tuhs - * 9MhfF+5lKER/9Ama/e7C61usaoUhR1OvpGWMfjewrFLCsyWlInscoZ1ad5YtcWGx - * MM7+BsTnK00fcXZuPHTPsiwQ0fMVeNM2a/e65aIivfzzHmb6gqUigNpfNYcqQsJJ - * Wwoc5hXVO92vugdHOHOiAUpfZZgNDZwgCTluMuI+KJ0QCb0dhF5w/TDA8z+vRwmW - * sz5WrA4F+T3LfwwLQfxJyHTnbAu38VlMMZP98iIobOX3AAkBw4+kTOCEedvmKt0f - * s7iSKrnnV6AyzRPEJUWknMF8xNFH7HDqkZf4Mv8cMM6e45K4kBGd17d3tcEFi2An - * 5l6S9hHtoyMhHjnAcyuHJbD9rGRgyOlbhSYTcbX/gKiECZj0kf8xHi20qntO3c+p - * jdpp97fIMnQTl5IDNxOy5h9MDLs/SYAR7iyF19RkIGc= - * -----END RSA PRIVATE KEY----- - */ - - /* - Certificate: - Data: - Version: 3 (0x2) - Serial Number: 2 (0x2) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=AN, ST=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com - Validity - Not Before: Mar 20 17:02:32 2009 GMT - Not After : Mar 20 17:02:32 2010 GMT - Subject: C=AN, ST=Android, L=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - RSA Public Key: (1024 bit) - Modulus (1024 bit): - 00:b4:c5:ed:df:30:42:6d:8b:af:4b:e4:9c:13:5e: - 83:23:cd:2f:ce:34:e2:43:d7:6c:72:bb:03:b3:b9: - 24:02:e0:cc:b5:8d:d6:92:41:04:2b:5c:94:b2:c3: - 9c:9d:56:f0:99:bc:0f:81:af:eb:54:ed:80:a6:a0: - c7:c2:43:05:04:7c:9c:7e:07:03:10:b9:bd:c5:16: - cf:19:dd:e3:4f:73:83:72:c5:66:e4:5b:14:c4:96: - d1:e3:24:0b:b6:d4:f7:84:2e:b1:e7:93:02:9d:f5: - da:aa:c1:d9:cc:5e:36:e9:8f:bf:8b:da:a7:45:82: - f2:b0:f5:a7:e4:e1:80:a3:17 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: - CA:FALSE - Netscape Comment: - OpenSSL Generated Certificate - X509v3 Subject Key Identifier: - 3B:5B:3D:DB:45:F5:8F:58:70:0B:FC:70:3E:31:2B:43:63:A9:FE:2B - X509v3 Authority Key Identifier: - keyid:E7:9B:7D:90:29:EA:90:0B:7F:08:41:76:4E:41:23:E8:43:2C:A9:03 - - Signature Algorithm: sha1WithRSAEncryption - 1c:7f:93:1c:59:21:88:15:45:4b:e0:9c:78:3a:88:3e:55:19: - 86:31:e8:53:3d:74:e2:4a:34:9f:92:17:4e:13:46:92:54:f8: - 43:eb:5e:03:4f:14:51:61:d2:04:b8:04:5a:31:eb:14:6a:18: - b0:20:03:92:0c:7f:07:c4:1b:f9:9e:7f:5f:ec:03:7a:c8:e3: - df:d3:94:6e:68:8a:3a:3d:e4:61:f3:e0:87:5d:40:d8:cb:99: - 4d:9a:7b:bc:95:7c:d2:9d:b7:04:9a:9a:63:89:cd:39:ec:32: - 60:0a:97:da:e9:50:a5:73:4a:a2:aa:9c:9b:a8:7f:5a:20:d6: - 48:bd - */ - String certificate3 = "-----BEGIN CERTIFICATE-----\n" - + "MIIC9jCCAl+gAwIBAgIBAjANBgkqhkiG9w0BAQUFADB5MQswCQYDVQQGEwJBTjEQ\n" - + "MA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5k\n" - + "cm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBh\n" - + "bmRyb2lkLmNvbTAeFw0wOTAzMjAxNzAyMzJaFw0xMDAzMjAxNzAyMzJaMIGLMQsw\n" - + "CQYDVQQGEwJBTjEQMA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEBxMHQW5kcm9pZDEQ\n" - + "MA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5k\n" - + "cm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTCBnzANBgkq\n" - + "hkiG9w0BAQEFAAOBjQAwgYkCgYEAtMXt3zBCbYuvS+ScE16DI80vzjTiQ9dscrsD\n" - + "s7kkAuDMtY3WkkEEK1yUssOcnVbwmbwPga/rVO2ApqDHwkMFBHycfgcDELm9xRbP\n" - + "Gd3jT3ODcsVm5FsUxJbR4yQLttT3hC6x55MCnfXaqsHZzF426Y+/i9qnRYLysPWn\n" - + "5OGAoxcCAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNT\n" - + "TCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFDtbPdtF9Y9YcAv8cD4x\n" - + "K0Njqf4rMB8GA1UdIwQYMBaAFOebfZAp6pALfwhBdk5BI+hDLKkDMA0GCSqGSIb3\n" - + "DQEBBQUAA4GBABx/kxxZIYgVRUvgnHg6iD5VGYYx6FM9dOJKNJ+SF04TRpJU+EPr\n" - + "XgNPFFFh0gS4BFox6xRqGLAgA5IMfwfEG/mef1/sA3rI49/TlG5oijo95GHz4Idd\n" - + "QNjLmU2ae7yVfNKdtwSammOJzTnsMmAKl9rpUKVzSqKqnJuof1og1ki9\n" - + "-----END CERTIFICATE-----"; - - ByteArrayInputStream certArray3 = new ByteArrayInputStream(certificate3 - .getBytes()); - - /* - * The key in DER format. - * Below is the same key in PEM format as reference - */ - byte[] key3Bytes = new byte[] { - (byte)0x30, (byte)0x82, (byte)0x02, (byte)0x76, (byte)0x02, (byte)0x01, (byte)0x00, - (byte)0x30, (byte)0x0d, (byte)0x06, (byte)0x09, (byte)0x2a, (byte)0x86, (byte)0x48, - (byte)0x86, (byte)0xf7, (byte)0x0d, (byte)0x01, (byte)0x01, (byte)0x01, (byte)0x05, - (byte)0x00, (byte)0x04, (byte)0x82, (byte)0x02, (byte)0x60, (byte)0x30, (byte)0x82, - (byte)0x02, (byte)0x5c, (byte)0x02, (byte)0x01, (byte)0x00, (byte)0x02, (byte)0x81, - (byte)0x81, (byte)0x00, (byte)0xb4, (byte)0xc5, (byte)0xed, (byte)0xdf, (byte)0x30, - (byte)0x42, (byte)0x6d, (byte)0x8b, (byte)0xaf, (byte)0x4b, (byte)0xe4, (byte)0x9c, - (byte)0x13, (byte)0x5e, (byte)0x83, (byte)0x23, (byte)0xcd, (byte)0x2f, (byte)0xce, - (byte)0x34, (byte)0xe2, (byte)0x43, (byte)0xd7, (byte)0x6c, (byte)0x72, (byte)0xbb, - (byte)0x03, (byte)0xb3, (byte)0xb9, (byte)0x24, (byte)0x02, (byte)0xe0, (byte)0xcc, - (byte)0xb5, (byte)0x8d, (byte)0xd6, (byte)0x92, (byte)0x41, (byte)0x04, (byte)0x2b, - (byte)0x5c, (byte)0x94, (byte)0xb2, (byte)0xc3, (byte)0x9c, (byte)0x9d, (byte)0x56, - (byte)0xf0, (byte)0x99, (byte)0xbc, (byte)0x0f, (byte)0x81, (byte)0xaf, (byte)0xeb, - (byte)0x54, (byte)0xed, (byte)0x80, (byte)0xa6, (byte)0xa0, (byte)0xc7, (byte)0xc2, - (byte)0x43, (byte)0x05, (byte)0x04, (byte)0x7c, (byte)0x9c, (byte)0x7e, (byte)0x07, - (byte)0x03, (byte)0x10, (byte)0xb9, (byte)0xbd, (byte)0xc5, (byte)0x16, (byte)0xcf, - (byte)0x19, (byte)0xdd, (byte)0xe3, (byte)0x4f, (byte)0x73, (byte)0x83, (byte)0x72, - (byte)0xc5, (byte)0x66, (byte)0xe4, (byte)0x5b, (byte)0x14, (byte)0xc4, (byte)0x96, - (byte)0xd1, (byte)0xe3, (byte)0x24, (byte)0x0b, (byte)0xb6, (byte)0xd4, (byte)0xf7, - (byte)0x84, (byte)0x2e, (byte)0xb1, (byte)0xe7, (byte)0x93, (byte)0x02, (byte)0x9d, - (byte)0xf5, (byte)0xda, (byte)0xaa, (byte)0xc1, (byte)0xd9, (byte)0xcc, (byte)0x5e, - (byte)0x36, (byte)0xe9, (byte)0x8f, (byte)0xbf, (byte)0x8b, (byte)0xda, (byte)0xa7, - (byte)0x45, (byte)0x82, (byte)0xf2, (byte)0xb0, (byte)0xf5, (byte)0xa7, (byte)0xe4, - (byte)0xe1, (byte)0x80, (byte)0xa3, (byte)0x17, (byte)0x02, (byte)0x03, (byte)0x01, - (byte)0x00, (byte)0x01, (byte)0x02, (byte)0x81, (byte)0x80, (byte)0x53, (byte)0xbc, - (byte)0x1f, (byte)0x1c, (byte)0x34, (byte)0x09, (byte)0x81, (byte)0x1e, (byte)0xa3, - (byte)0xfb, (byte)0x5e, (byte)0x90, (byte)0xa1, (byte)0x34, (byte)0x35, (byte)0x40, - (byte)0x9f, (byte)0x29, (byte)0xd6, (byte)0xb5, (byte)0x8e, (byte)0x5d, (byte)0x68, - (byte)0x6a, (byte)0xf6, (byte)0x96, (byte)0x03, (byte)0xf7, (byte)0xfa, (byte)0xf9, - (byte)0x60, (byte)0x4f, (byte)0xea, (byte)0xe2, (byte)0xea, (byte)0x29, (byte)0x8b, - (byte)0x23, (byte)0x8c, (byte)0x9f, (byte)0xdd, (byte)0x49, (byte)0x8f, (byte)0xa8, - (byte)0xa6, (byte)0x62, (byte)0x07, (byte)0x44, (byte)0x79, (byte)0xa1, (byte)0xaf, - (byte)0xf9, (byte)0x1d, (byte)0x98, (byte)0xbf, (byte)0x85, (byte)0x28, (byte)0x03, - (byte)0x87, (byte)0x14, (byte)0x20, (byte)0xba, (byte)0xd4, (byte)0x96, (byte)0x61, - (byte)0x2a, (byte)0xd0, (byte)0xaa, (byte)0x30, (byte)0x19, (byte)0x4b, (byte)0x40, - (byte)0x35, (byte)0xb0, (byte)0x79, (byte)0x0b, (byte)0x7f, (byte)0xd7, (byte)0xcd, - (byte)0x64, (byte)0xd9, (byte)0x93, (byte)0x38, (byte)0xe2, (byte)0x59, (byte)0xe0, - (byte)0x9e, (byte)0x3a, (byte)0x25, (byte)0x27, (byte)0xa2, (byte)0xd9, (byte)0x20, - (byte)0xb0, (byte)0x45, (byte)0x5f, (byte)0x6c, (byte)0x15, (byte)0x6f, (byte)0x10, - (byte)0x55, (byte)0xa7, (byte)0xf9, (byte)0x3d, (byte)0x92, (byte)0x3c, (byte)0x7c, - (byte)0x23, (byte)0x1b, (byte)0xc0, (byte)0xb5, (byte)0x17, (byte)0x41, (byte)0x5e, - (byte)0x8c, (byte)0xdc, (byte)0x25, (byte)0x1d, (byte)0x35, (byte)0x2b, (byte)0xd3, - (byte)0x97, (byte)0x1a, (byte)0x6f, (byte)0xae, (byte)0xeb, (byte)0xf5, (byte)0xf9, - (byte)0x02, (byte)0x41, (byte)0x00, (byte)0xd7, (byte)0x3e, (byte)0xed, (byte)0x70, - (byte)0xfe, (byte)0xee, (byte)0x0e, (byte)0x30, (byte)0x29, (byte)0xfa, (byte)0xd7, - (byte)0x38, (byte)0xcf, (byte)0x8e, (byte)0xc1, (byte)0x9c, (byte)0x78, (byte)0x06, - (byte)0x2d, (byte)0xda, (byte)0x33, (byte)0x58, (byte)0xa1, (byte)0x7b, (byte)0xbf, - (byte)0x00, (byte)0xb9, (byte)0xdf, (byte)0xea, (byte)0x65, (byte)0x86, (byte)0xbb, - (byte)0xcc, (byte)0x83, (byte)0xce, (byte)0xde, (byte)0xc3, (byte)0xf8, (byte)0x89, - (byte)0xf5, (byte)0x9f, (byte)0xa6, (byte)0x1d, (byte)0xc9, (byte)0xfb, (byte)0x98, - (byte)0xa1, (byte)0x2e, (byte)0xe0, (byte)0x57, (byte)0x6e, (byte)0xbd, (byte)0x57, - (byte)0x20, (byte)0xf9, (byte)0x6b, (byte)0x13, (byte)0x42, (byte)0x9d, (byte)0x8d, - (byte)0x66, (byte)0x4d, (byte)0x7a, (byte)0x2d, (byte)0x02, (byte)0x41, (byte)0x00, - (byte)0xd7, (byte)0x00, (byte)0x18, (byte)0x54, (byte)0xe8, (byte)0x37, (byte)0xdb, - (byte)0xf8, (byte)0x98, (byte)0x7b, (byte)0x18, (byte)0x33, (byte)0xf6, (byte)0x28, - (byte)0xa8, (byte)0x8c, (byte)0xd9, (byte)0xfd, (byte)0x4c, (byte)0x4e, (byte)0x41, - (byte)0x73, (byte)0x2e, (byte)0x79, (byte)0x31, (byte)0xcc, (byte)0x7d, (byte)0x42, - (byte)0xb7, (byte)0xa1, (byte)0xd2, (byte)0xbc, (byte)0x1f, (byte)0x62, (byte)0xcf, - (byte)0x15, (byte)0x7c, (byte)0x62, (byte)0x97, (byte)0x70, (byte)0xf1, (byte)0x15, - (byte)0xf1, (byte)0x33, (byte)0xa1, (byte)0x9d, (byte)0xbb, (byte)0x5f, (byte)0xd7, - (byte)0x5a, (byte)0xf9, (byte)0x24, (byte)0x58, (byte)0xac, (byte)0x86, (byte)0x6a, - (byte)0xed, (byte)0xd4, (byte)0x84, (byte)0xe4, (byte)0x3f, (byte)0xfe, (byte)0xb0, - (byte)0xd3, (byte)0x02, (byte)0x41, (byte)0x00, (byte)0xd4, (byte)0xb7, (byte)0x84, - (byte)0xb2, (byte)0x39, (byte)0xce, (byte)0x0b, (byte)0x49, (byte)0x80, (byte)0x03, - (byte)0x3c, (byte)0xb5, (byte)0x11, (byte)0x32, (byte)0x34, (byte)0x96, (byte)0xac, - (byte)0x6a, (byte)0xf6, (byte)0xdf, (byte)0x80, (byte)0x04, (byte)0xe4, (byte)0x39, - (byte)0xc6, (byte)0x0e, (byte)0x32, (byte)0xa3, (byte)0x5e, (byte)0x23, (byte)0x0d, - (byte)0x9f, (byte)0x04, (byte)0xc3, (byte)0x72, (byte)0x2a, (byte)0xe6, (byte)0xa2, - (byte)0xf5, (byte)0xbc, (byte)0x3f, (byte)0x15, (byte)0x4c, (byte)0xb5, (byte)0x33, - (byte)0x26, (byte)0xa8, (byte)0x8c, (byte)0x09, (byte)0xfb, (byte)0x7e, (byte)0x1e, - (byte)0x32, (byte)0x40, (byte)0x0d, (byte)0x1d, (byte)0xcb, (byte)0x7f, (byte)0xf6, - (byte)0xf2, (byte)0x29, (byte)0x9b, (byte)0x01, (byte)0xd5, (byte)0x02, (byte)0x40, - (byte)0x24, (byte)0x26, (byte)0x1c, (byte)0xf1, (byte)0x31, (byte)0xb6, (byte)0x2a, - (byte)0xa3, (byte)0x0a, (byte)0xa8, (byte)0x2f, (byte)0xb2, (byte)0x94, (byte)0xe1, - (byte)0xd3, (byte)0x2d, (byte)0x13, (byte)0x7d, (byte)0xd6, (byte)0x35, (byte)0x96, - (byte)0x25, (byte)0x92, (byte)0x9b, (byte)0xc7, (byte)0xf6, (byte)0xb4, (byte)0xdc, - (byte)0xe1, (byte)0xd9, (byte)0x30, (byte)0x80, (byte)0x76, (byte)0xda, (byte)0x7b, - (byte)0x2d, (byte)0x06, (byte)0xa3, (byte)0xe1, (byte)0x08, (byte)0x99, (byte)0x50, - (byte)0x72, (byte)0x24, (byte)0x97, (byte)0x38, (byte)0xd9, (byte)0x07, (byte)0x4d, - (byte)0x43, (byte)0x3b, (byte)0x7e, (byte)0x93, (byte)0xf6, (byte)0x36, (byte)0x07, - (byte)0x86, (byte)0x83, (byte)0x63, (byte)0xf0, (byte)0xa8, (byte)0x9d, (byte)0xdf, - (byte)0x07, (byte)0x02, (byte)0x40, (byte)0x3e, (byte)0x58, (byte)0x03, (byte)0xbf, - (byte)0xea, (byte)0x3e, (byte)0x34, (byte)0x2c, (byte)0xb7, (byte)0xc3, (byte)0x09, - (byte)0xe9, (byte)0xf4, (byte)0x43, (byte)0x41, (byte)0xc4, (byte)0x7c, (byte)0x6e, - (byte)0x75, (byte)0x72, (byte)0x5d, (byte)0xfc, (byte)0xa3, (byte)0x75, (byte)0x1d, - (byte)0xa0, (byte)0xee, (byte)0xc2, (byte)0x1f, (byte)0x71, (byte)0xb0, (byte)0xf3, - (byte)0x1d, (byte)0xec, (byte)0x81, (byte)0xdb, (byte)0x45, (byte)0xe5, (byte)0x6a, - (byte)0xe8, (byte)0xe0, (byte)0x64, (byte)0x90, (byte)0xff, (byte)0xb9, (byte)0xf8, - (byte)0x12, (byte)0xed, (byte)0x55, (byte)0x5c, (byte)0x9b, (byte)0x81, (byte)0xcd, - (byte)0xbb, (byte)0x06, (byte)0x91, (byte)0xfe, (byte)0x27, (byte)0x2c, (byte)0x3a, - (byte)0xed, (byte)0x96, (byte)0x3b, (byte)0xfe - }; - - /* - * The same key in PEM format. - * The DER version of this key was created using - * - * openssl pkcs8 -topk8 -nocrypt -in key1.pem - * -inform PEM -out key1.der -outform DER - * - * -----BEGIN RSA PRIVATE KEY----- - * Proc-Type: 4,ENCRYPTED - * DEK-Info: DES-EDE3-CBC,0EE6B33EC2D92297 - * - * r7lbWwtlmubgMG020XiOStqgrvPkP1hTrbOV7Gh2IVNTyXWyA8UriQlPyqBQNzy2 - * 5+Z+JUqzYoLCGY0fQ95ck+ya/wHJQX4OSKFOZwQKpU7pEY9wN1YPa7U9ZnyCPGtB - * +ejvHuIMJhE5wq9Y1iEDIlON++onWTf4T36Sz3OQ8gEJbnx3x+UjcCINooj7kOeM - * giCi5yJEOJaf4fkRioUh6S7cm/msTH3ID33rrvTjk7cD8mGzzTy4hWyKaK4K9GbC - * dOvSORM9mVwTWMUdu1wJ5uyadwBhpSIhC/qpP8Je60nFy8YJlzB2FaMUpAuIOM7B - * EVN2uAMDNOpGzcOJPbLig8smk2lA4+y1T3gFd9paskSjD9B8+/3KuagWEEQQL7T4 - * YK3xtjzXwEp6OdG2QjD4ZcK5D0MKuYPF3PszwzlCnBG/On6wIvIiTPWBn/G2u59D - * gJPV7V3Jipn0iYYN+i7T5TNoT7Vko8s3BRpVSrlFUFFhtQPad6NcxGNNH5L1g3fF - * +dp4TnG64PCQZtuu6I6gfuMXztOwQtEpxxHo9WktlCpwL0tT/tpx+zOVbLvgusjB - * QKYCIplbSI7VtpOfcJ3kTTAWSOGZli4FayB/Dplf/FXN6ZwwASw09ioVQc/CFdLk - * Xw05elxV8/AFvm+/VkUHK5JJSp32WMgAJA+XrUsOb5lw1Tl3Hlj9KHALp+Pt/i7N - * +LPnxrpuTry31APt8aRup/pWOLa+f97Hz+arp4wJa5LK+GtTTtoI4+QZp5qzR/jy - * oM+DoKtK+1WsCU7teJwEWXV/ayo1TEFEhcY0F7IAPCzDlG3XOFmulQ== - * -----END RSA PRIVATE KEY----- - */ - - @Override - protected void setUp() { - String defAlg = KeyManagerFactory.getDefaultAlgorithm(); - try { - factory = KeyManagerFactory.getInstance(defAlg); - } catch (NoSuchAlgorithmException e) { - fail("could not get default KeyManagerFactory"); - } - } - - void init(String name) { - keyType = name; - try { - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - KeyFactory kf = KeyFactory.getInstance("RSA"); - keyTest = KeyStore.getInstance(KeyStore.getDefaultType()); - keyTest.load(null, "1234".toCharArray()); - if (keyType.equals(CLIENT)) { - keys = new PrivateKey[3]; - keys[0] = kf.generatePrivate(new PKCS8EncodedKeySpec(keyBytes)); - keys[1] = kf.generatePrivate(new PKCS8EncodedKeySpec(key2Bytes)); - keys[2] = kf.generatePrivate(new PKCS8EncodedKeySpec(key3Bytes)); - cert = new X509Certificate[3]; - cert[0] = (X509Certificate) cf.generateCertificate(certArray); - cert[1] = (X509Certificate) cf.generateCertificate(certArray2); - cert[2] = (X509Certificate) cf.generateCertificate(certArray3); - keyTest.setKeyEntry("clientKey_01", keys[0], PASSWORD, new X509Certificate[] {cert[0]}); - keyTest.setKeyEntry("clientKey_02", keys[1], PASSWORD, new X509Certificate[] {cert[0], cert[1]}); - keyTest.setKeyEntry("clientKey_03", keys[2], PASSWORD, new X509Certificate[] {cert[0], cert[2]}); - keyTest.setCertificateEntry("clientAlias_01", cert[0]); - keyTest.setCertificateEntry("clientAlias_02", cert[0]); - keyTest.setCertificateEntry("clientAlias_03", cert[1]); - } else if (keyType.equals(SERVER)) { - keys = new PrivateKey[1]; - keys[0] = kf.generatePrivate(new PKCS8EncodedKeySpec(keyBytes)); - cert = new X509Certificate[1]; - cert[0] = (X509Certificate) cf.generateCertificate(certArray3); - keyTest.setKeyEntry("serverKey_00", keys[0], PASSWORD, new X509Certificate[] {cert[0]}); - keyTest.setCertificateEntry("serverAlias_00", cert[0]); - } - } catch (Exception ex) { - ex.printStackTrace(); - throw new IllegalArgumentException(ex.getMessage()); - } - try { - factory.init(keyTest, "1234".toCharArray()); - } catch (Exception e) { - fail("Could't init the KeyManagerFactory"); - } - manager = (X509KeyManager) factory.getKeyManagers()[0]; - } - - /** - * X509KeyManager#getClientAliases(String keyType, Principal[] issuers) - */ - public void test_getClientAliases() { - init(CLIENT); - assertNull(manager.getClientAliases(null, null)); - assertNull(manager.getClientAliases("", null)); - String[] resArray = manager.getClientAliases(TYPE_RSA, null); - assertNotNull(resArray); - assertEquals(3, resArray.length); - assertKnownAliases(resArray); - } - - /** - * X509KeyManager#chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) - */ - public void test_chooseClientAlias() { - init(CLIENT); - assertNull(manager.chooseClientAlias(null, null, new Socket())); - assertNull(manager.chooseClientAlias(new String[0], null, new Socket())); - assertNull(manager.chooseClientAlias(new String[]{"BOGUS"}, null, new Socket())); - String res = manager.chooseClientAlias(new String[]{TYPE_RSA}, null, null); - assertNotNull(res); - assertKnownAlias(res); - } - - /** - * X509KeyManager#getServerAliases(String keyType, Principal[] issuers) - */ - public void test_getServerAliases() { - init(SERVER); - assertNull(manager.getServerAliases(null, null)); - assertNull(manager.getServerAliases("", null)); - String[] resArray = manager.getServerAliases(TYPE_RSA, null); - assertNotNull(resArray); - assertEquals("Incorrect length", 1, resArray.length); - assertEquals("Incorrect aliase", "serverkey_00", resArray[0].toLowerCase()); - } - - /** - * X509KeyManager#chooseServerAlias(String keyType, Principal[] issuers, Socket socket) - */ - public void test_chooseServerAlias() { - init(SERVER); - assertNull(manager.chooseServerAlias(null, null, new Socket())); - assertNull(manager.chooseServerAlias("", null, new Socket())); - String res = manager.chooseServerAlias(TYPE_RSA, null, null); - assertNotNull(res); - assertEquals("serverkey_00", res.toLowerCase()); - res = manager.chooseServerAlias(TYPE_RSA, null, new Socket()); - assertNotNull(res); - assertEquals("serverkey_00", res.toLowerCase()); - } - - /** - * X509KeyManager#getCertificateChain(String alias) - */ - public void test_getCertificateChain() { - init(SERVER); - assertNull("Not NULL for NULL parameter", manager.getCertificateChain(null)); - assertNull("Not NULL for empty parameter",manager.getCertificateChain("")); - assertNull("Not NULL for clientAlias_01 parameter", manager.getCertificateChain("clientAlias_01")); - assertNull("Not NULL for serverAlias_00 parameter", manager.getCertificateChain("serverAlias_00")); - } - - /** - * X509KeyManager#getPrivateKey(String alias) - */ - public void test_getPrivateKey() { - init(CLIENT); - assertNull("Not NULL for NULL parameter", manager.getPrivateKey(null)); - assertNull("Not NULL for serverAlias_00 parameter", manager.getPrivateKey("serverAlias_00")); - assertNull("Not NULL for clientAlias_02 parameter", manager.getPrivateKey("clientAlias_02")); - } - - - private void assertKnownAliases(String[] aliases) { - for (String alias : aliases) { - assertKnownAlias(alias); - } - } - - private void assertKnownAlias(String alias) { - String a = alias.toLowerCase(); - boolean okay = a.equals("clientkey_01") || a.equals("clientkey_02") || a.equals("clientkey_03"); - assertTrue("Expected one of clientkey_01, clientkey_02, clientkey_03. Received: " + alias, okay); - } -} - diff --git a/luni/src/test/java/tests/api/javax/net/ssl/X509TrustManagerTest.java b/luni/src/test/java/tests/api/javax/net/ssl/X509TrustManagerTest.java deleted file mode 100644 index ade0eca..0000000 --- a/luni/src/test/java/tests/api/javax/net/ssl/X509TrustManagerTest.java +++ /dev/null @@ -1,149 +0,0 @@ -package tests.api.javax.net.ssl; - -import java.io.ByteArrayInputStream; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import javax.net.ssl.X509TrustManager; -import junit.framework.TestCase; -import org.apache.harmony.security.tests.support.cert.TestUtils; -import org.apache.harmony.xnet.tests.support.X509TrustManagerImpl; - -public class X509TrustManagerTest extends TestCase { - - private X509Certificate[] setX509Certificate() throws Exception { - CertificateFactory certFact = CertificateFactory.getInstance("X.509"); - X509Certificate pemCert = (X509Certificate) certFact.generateCertificate( - new ByteArrayInputStream(TestUtils.getX509Certificate_v3())); - X509Certificate[] xcert = { pemCert }; - return xcert; - } - - private X509Certificate[] setInvalid() throws Exception { - CertificateFactory certFact = CertificateFactory.getInstance("X.509"); - X509Certificate pemCert = (X509Certificate) certFact.generateCertificate( - new ByteArrayInputStream(TestUtils.getX509Certificate_v1())); - X509Certificate[] xcert = { pemCert }; - return xcert; - } - - public void test_checkClientTrusted_01() throws Exception { - X509TrustManagerImpl xtm = new X509TrustManagerImpl(); - X509Certificate[] xcert = null; - - try { - xtm.checkClientTrusted(xcert, "SSL"); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException expected) { - } - - xcert = new X509Certificate[0]; - try { - xtm.checkClientTrusted(xcert, "SSL"); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException expected) { - } - - xcert = setX509Certificate(); - try { - xtm.checkClientTrusted(xcert, null); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException expected) { - } - - try { - xtm.checkClientTrusted(xcert, ""); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException expected) { - } - } - - /** - * javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[] chain, String authType) - */ - public void test_checkClientTrusted_02() throws Exception { - X509TrustManagerImpl xtm = new X509TrustManagerImpl(); - X509Certificate[] xcert = setInvalid(); - - try { - xtm.checkClientTrusted(xcert, "SSL"); - fail("CertificateException wasn't thrown"); - } catch (CertificateException expected) { - } - } - - /** - * javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[] chain, String authType) - */ - public void test_checkClientTrusted_03() throws Exception { - X509TrustManagerImpl xtm = new X509TrustManagerImpl(); - X509Certificate[] xcert = setX509Certificate(); - xtm.checkClientTrusted(xcert, "SSL"); - } - - /** - * javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[] chain, String authType) - */ - public void test_checkServerTrusted_01() throws Exception { - X509TrustManagerImpl xtm = new X509TrustManagerImpl(); - X509Certificate[] xcert = null; - - try { - xtm.checkServerTrusted(xcert, "SSL"); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException expected) { - } - - xcert = new X509Certificate[0]; - try { - xtm.checkServerTrusted(xcert, "SSL"); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException expected) { - } - - xcert = setX509Certificate(); - try { - xtm.checkServerTrusted(xcert, null); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException expected) { - } - - try { - xtm.checkServerTrusted(xcert, ""); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException expected) { - } - } - - /** - * javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[] chain, String authType) - */ - public void test_checkServerTrusted_02() throws Exception { - X509TrustManagerImpl xtm = new X509TrustManagerImpl(); - X509Certificate[] xcert = setInvalid(); - - try { - xtm.checkServerTrusted(xcert, "SSL"); - fail("CertificateException wasn't thrown"); - } catch (CertificateException expected) { - } - } - - /** - * javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[] chain, String authType) - */ - public void test_checkServerTrusted_03() throws Exception { - X509TrustManagerImpl xtm = new X509TrustManagerImpl(); - X509Certificate[] xcert = setX509Certificate(); - xtm.checkServerTrusted(xcert, "SSL"); - } - - /** - * javax.net.ssl.X509TrustManager#getAcceptedIssuers() - */ - public void test_getAcceptedIssuers() throws Exception { - X509TrustManagerImpl xtm = new X509TrustManagerImpl(); - assertNotNull(xtm.getAcceptedIssuers()); - } - -} diff --git a/luni/src/test/java/tests/api/javax/security/auth/CallbackHandlerTest.java b/luni/src/test/java/tests/api/javax/security/auth/CallbackHandlerTest.java deleted file mode 100644 index 76c860a..0000000 --- a/luni/src/test/java/tests/api/javax/security/auth/CallbackHandlerTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.security.auth; - -import junit.framework.TestCase; - -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; - -/** - * Tests for <code>CallbackHandler</code> class constructors and methods. - * - */ -public class CallbackHandlerTest extends TestCase { - - /** - * javax.security.auth.callback.CallbackHandler#handle(Callback[] callbacks) - */ - public void test_CallbackHandler() { - CallbackHandlerImpl ch = new CallbackHandlerImpl(); - assertFalse(ch.called); - ch.handle(null); - assertTrue(ch.called); - } - - private class CallbackHandlerImpl implements CallbackHandler { - boolean called = false; - public void handle(Callback[] callbacks) { - called = true; - } - } -} diff --git a/luni/src/test/java/tests/api/javax/security/auth/DestroyFailedExceptionTest.java b/luni/src/test/java/tests/api/javax/security/auth/DestroyFailedExceptionTest.java deleted file mode 100644 index 4472241..0000000 --- a/luni/src/test/java/tests/api/javax/security/auth/DestroyFailedExceptionTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.security.auth; - -import junit.framework.TestCase; - -import javax.security.auth.DestroyFailedException; - -/** - * Tests for <code>DestroyFailedException</code> class constructors and methods. - * - */ -public class DestroyFailedExceptionTest extends TestCase { - - private static String[] msgs = { - "", - "Check new message", - "Check new message Check new message Check new message Check new message Check new message" }; - - - /** - * javax.security.auth.DestroyFailedException#DestroyFailedException() - * Assertion: constructs DestroyFailedException with no detail message - */ - public void testDestroyFailedException01() { - DestroyFailedException dfE = new DestroyFailedException(); - assertNull("getMessage() must return null.", dfE.getMessage()); - assertNull("getCause() must return null", dfE.getCause()); - } - - /** - * javax.security.auth.DestroyFailedException#DestroyFailedException(String msg) - * Assertion: constructs with not null parameter. - */ - public void testDestroyFailedException02() { - DestroyFailedException dfE; - for (int i = 0; i < msgs.length; i++) { - dfE = new DestroyFailedException(msgs[i]); - assertEquals("getMessage() must return: ".concat(msgs[i]), dfE.getMessage(), msgs[i]); - assertNull("getCause() must return null", dfE.getCause()); - } - } - - /** - * javax.security.auth.DestroyFailedException#DestroyFailedException(String msg) - * Assertion: constructs with null parameter. - */ - public void testDestroyFailedException03() { - String msg = null; - DestroyFailedException dfE = new DestroyFailedException(msg); - assertNull("getMessage() must return null.", dfE.getMessage()); - assertNull("getCause() must return null", dfE.getCause()); - } -} diff --git a/luni/src/test/java/tests/api/javax/security/auth/DestroyableTest.java b/luni/src/test/java/tests/api/javax/security/auth/DestroyableTest.java deleted file mode 100644 index 4ae47ce..0000000 --- a/luni/src/test/java/tests/api/javax/security/auth/DestroyableTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.security.auth; - -import junit.framework.TestCase; - -import javax.security.auth.Destroyable; -import javax.security.auth.DestroyFailedException; - - -/** - * Tests for <code>Destroyable</code> class constructors and methods. - * - */ -public class DestroyableTest extends TestCase { - - /** - * javax.security.auth.Destroyable#destroy() - * javax.security.auth.Destroyable#isDestroyed() - */ - public void test_destroy() { - myDestroyable md = new myDestroyable(); - try { - assertFalse(md.isDestroyed()); - md.destroy(); - assertTrue(md.isDestroyed()); - } catch (Exception e) { - fail("Unexpected exception " + e); - } - } - - private class myDestroyable implements Destroyable { - - boolean destroyDone = false; - - myDestroyable() { - } - - public void destroy() throws DestroyFailedException { - destroyDone = true; - } - - public boolean isDestroyed() { - return destroyDone; - } - } -} - - diff --git a/luni/src/test/java/tests/api/javax/security/auth/LoginExceptionTest.java b/luni/src/test/java/tests/api/javax/security/auth/LoginExceptionTest.java deleted file mode 100644 index 307d401..0000000 --- a/luni/src/test/java/tests/api/javax/security/auth/LoginExceptionTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.security.auth; - -import junit.framework.TestCase; - -import javax.security.auth.login.LoginException; - -/** - * Tests for <code>LoginException</code> class constructors and methods. - * - */ -public class LoginExceptionTest extends TestCase { - - private static String[] msgs = { - "", - "Check new message", - "Check new message Check new message Check new message Check new message Check new message" }; - - - /** - * javax.security.auth.login.LoginException#LoginException() - * Assertion: constructs LoginException with no detail message - */ - public void testLoginException01() { - LoginException lE = new LoginException(); - assertNull("getMessage() must return null.", lE.getMessage()); - assertNull("getCause() must return null", lE.getCause()); - } - - /** - * javax.security.auth.login.LoginException#LoginException(String msg) - * Assertion: constructs with not null parameter. - */ - public void testLoginException02() { - LoginException lE; - for (int i = 0; i < msgs.length; i++) { - lE = new LoginException(msgs[i]); - assertEquals("getMessage() must return: ".concat(msgs[i]), lE.getMessage(), msgs[i]); - assertNull("getCause() must return null", lE.getCause()); - } - } - - /** - * javax.security.auth.login.LoginException#LoginException(String msg) - * Assertion: constructs with null parameter. - */ - public void testLoginException03() { - String msg = null; - LoginException lE = new LoginException(msg); - assertNull("getMessage() must return null.", lE.getMessage()); - assertNull("getCause() must return null", lE.getCause()); - } -} diff --git a/luni/src/test/java/tests/api/javax/security/auth/PasswordCallbackTest.java b/luni/src/test/java/tests/api/javax/security/auth/PasswordCallbackTest.java deleted file mode 100644 index cdd992b..0000000 --- a/luni/src/test/java/tests/api/javax/security/auth/PasswordCallbackTest.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.security.auth; - -import junit.framework.TestCase; - -import javax.security.auth.callback.PasswordCallback; - -/** - * Tests for <code>PasswordCallback</code> class constructors and methods. - * - */ -public class PasswordCallbackTest extends TestCase { - - /** - * javax.security.auth.callback.PasswordCallback#PasswordCallback(String prompt, boolean echoOn) - * javax.security.auth.callback.PasswordCallback#getPrompt() - * javax.security.auth.callback.PasswordCallback#isEchoOn() - */ - public void test_PasswordCallback() { - String prompt = "promptTest"; - - try { - PasswordCallback pc = new PasswordCallback(prompt, true); - assertNotNull("Null object returned", pc); - assertEquals(prompt, pc.getPrompt()); - assertEquals(true, pc.isEchoOn()); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - - try { - PasswordCallback pc = new PasswordCallback(prompt, false); - assertNotNull("Null object returned", pc); - assertEquals(prompt, pc.getPrompt()); - assertEquals(false, pc.isEchoOn()); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - - try { - PasswordCallback pc = new PasswordCallback(null, true); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException npe) { - } - - try { - PasswordCallback pc = new PasswordCallback("", true); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException npe) { - } - } - - /** - * javax.security.auth.callback.PasswordCallback#getPassword() - * javax.security.auth.callback.PasswordCallback#setPassword(char[] password) - * javax.security.auth.callback.PasswordCallback#clearPassword() - */ - public void test_Password() { - String prompt = "promptTest"; - char[] psw1 = "testPassword".toCharArray(); - char[] psw2 = "newPassword".toCharArray(); - PasswordCallback pc = new PasswordCallback(prompt, true); - - try { - assertNull(pc.getPassword()); - pc.setPassword(psw1); - assertEquals(psw1.length, pc.getPassword().length); - pc.setPassword(null); - assertNull(pc.getPassword()); - pc.setPassword(psw2); - char[] res = pc.getPassword(); - assertEquals(psw2.length, res.length); - for (int i = 0; i < res.length; i++) { - assertEquals("Incorrect password was returned", psw2[i], res[i]); - } - pc.clearPassword(); - res = pc.getPassword(); - if (res.equals(psw2)) { - fail("Incorrect password was returned after clear"); - } - pc.setPassword(psw1); - res = pc.getPassword(); - assertEquals(psw1.length, res.length); - for (int i = 0; i < res.length; i++) { - assertEquals("Incorrect result", psw1[i], res[i]); - } - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - } -} diff --git a/luni/src/test/java/tests/api/javax/security/auth/SubjectTest.java b/luni/src/test/java/tests/api/javax/security/auth/SubjectTest.java deleted file mode 100644 index 05741a9..0000000 --- a/luni/src/test/java/tests/api/javax/security/auth/SubjectTest.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.security.auth; - -import junit.framework.TestCase; - -import javax.security.auth.AuthPermission; -import javax.security.auth.PrivateCredentialPermission; -import javax.security.auth.Subject; - -import java.util.Set; -import java.util.HashSet; -import java.security.Permission; -import java.security.Principal; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.ProtectionDomain; - -/** - * Tests for <code>Subject</code> class constructors and methods. - * - */ -public class SubjectTest extends TestCase { - - /** - * javax.security.auth.Subject#Subject() - */ - public void test_Constructor_01() { - try { - Subject s = new Subject(); - assertNotNull("Null object returned", s); - assertTrue("Set of principal is not empty", s.getPrincipals().isEmpty()); - assertTrue("Set of private credentials is not empty", s.getPrivateCredentials().isEmpty()); - assertTrue("Set of public credentials is not empty", s.getPublicCredentials().isEmpty()); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - } - - /** - * javax.security.auth.Subject#doAs(Subject subject, PrivilegedAction action) - */ - public void test_doAs_01() { - Subject subj = new Subject(); - PrivilegedAction<Object> pa = new myPrivilegedAction(); - PrivilegedAction<Object> paNull = null; - - try { - Object obj = Subject.doAs(null, pa); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - - try { - Object obj = Subject.doAs(subj, pa); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - - try { - Object obj = Subject.doAs(subj, paNull); - fail("NullPointerException wasn't thrown"); - } catch (NullPointerException npe) { - } - } - - /** - * javax.security.auth.Subject#doAs(Subject subject, PrivilegedExceptionAction action) - */ - public void test_doAs_02() { - Subject subj = new Subject(); - PrivilegedExceptionAction<Object> pea = new myPrivilegedExceptionAction(); - PrivilegedExceptionAction<Object> peaNull = null; - - try { - Object obj = Subject.doAs(null, pea); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - - try { - Object obj = Subject.doAs(subj, pea); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - - try { - Object obj = Subject.doAs(subj, peaNull); - fail("NullPointerException wasn't thrown"); - } catch (NullPointerException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of NullPointerException"); - } - - try { - Subject.doAs(subj, new PrivilegedExceptionAction<Object>(){ - public Object run() throws PrivilegedActionException { - throw new PrivilegedActionException(null); - } - }); - fail("PrivilegedActionException wasn't thrown"); - } catch (PrivilegedActionException e) { - } - } - - /** - * javax.security.auth.Subject#doAsPrivileged(Subject subject, - * PrivilegedAction action, - * AccessControlContext acc) - */ - public void test_doAsPrivileged_01() { - Subject subj = new Subject(); - PrivilegedAction<Object> pa = new myPrivilegedAction(); - PrivilegedAction<Object> paNull = null; - AccessControlContext acc = AccessController.getContext(); - - try { - Object obj = Subject.doAsPrivileged(null, pa, acc); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - - try { - Object obj = Subject.doAsPrivileged(subj, pa, acc); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - - try { - Object obj = Subject.doAsPrivileged(subj, paNull, acc); - fail("NullPointerException wasn't thrown"); - } catch (NullPointerException npe) { - } - } - - /** - * javax.security.auth.Subject#doAsPrivileged(Subject subject, - * PrivilegedExceptionAction action, - * AccessControlContext acc) - */ - public void test_doAsPrivileged_02() { - Subject subj = new Subject(); - PrivilegedExceptionAction<Object> pea = new myPrivilegedExceptionAction(); - PrivilegedExceptionAction<Object> peaNull = null; - AccessControlContext acc = AccessController.getContext(); - - try { - Object obj = Subject.doAsPrivileged(null, pea, acc); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - - try { - Object obj = Subject.doAsPrivileged(subj, pea, acc); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - - try { - Object obj = Subject.doAsPrivileged(subj, peaNull, acc); - fail("NullPointerException wasn't thrown"); - } catch (NullPointerException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of NullPointerException"); - } - - try { - Subject.doAsPrivileged(subj, new PrivilegedExceptionAction<Object>(){ - public Object run() throws PrivilegedActionException { - throw new PrivilegedActionException(null); - } - }, acc); - fail("PrivilegedActionException wasn't thrown"); - } catch (PrivilegedActionException e) { - } - } - - /** - * javax.security.auth.Subject#getSubject(AccessControlContext acc) - */ - public void test_getSubject() { - Subject subj = new Subject(); - AccessControlContext acc = new AccessControlContext(new ProtectionDomain[0]); - - try { - assertNull(Subject.getSubject(acc)); - } catch (Exception e) { - fail("Unexpected exception " + e); - } - } - - /** - * javax.security.auth.Subject#toString() - */ - public void test_toString() { - Subject subj = new Subject(); - - try { - assertNotNull("Null returned", subj.toString()); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - } - - /** - * javax.security.auth.Subject#hashCode() - */ - public void test_hashCode() { - Subject subj = new Subject(); - - try { - assertNotNull("Null returned", subj.hashCode()); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - } -} - - -class myPrivilegedAction implements PrivilegedAction <Object> { - myPrivilegedAction(){} - public Object run() { - return new Object(); - } -} - -class myPrivilegedExceptionAction implements PrivilegedExceptionAction <Object> { - myPrivilegedExceptionAction(){} - public Object run() { - return new Object(); - } -} diff --git a/luni/src/test/java/tests/api/javax/security/auth/UnsupportedCallbackExceptionTest.java b/luni/src/test/java/tests/api/javax/security/auth/UnsupportedCallbackExceptionTest.java deleted file mode 100644 index abef563..0000000 --- a/luni/src/test/java/tests/api/javax/security/auth/UnsupportedCallbackExceptionTest.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.security.auth; - -import junit.framework.TestCase; - -import javax.security.auth.callback.UnsupportedCallbackException; -import javax.security.auth.callback.Callback; - -/** - * Tests for <code>UnsupportedCallbackException</code> class constructors and methods. - * - */ -public class UnsupportedCallbackExceptionTest extends TestCase { - - private static String[] msgs = { - "", - "Check new message", - "Check new message Check new message Check new message Check new message Check new message" }; - - - /** - * javax.security.auth.callback.UnsupportedCallbackExceptionTest#UnsupportedCallbackException(Callback callback) - * javax.security.auth.callback.UnsupportedCallbackExceptionTest#getCallback() - * Assertion: constructs with null parameter. - */ - public void testUnsupportedCallbackException01() { - Callback c = null; - UnsupportedCallbackException ucE = new UnsupportedCallbackException(c); - assertNull("getMessage() must return null.", ucE.getMessage()); - assertNull("getCallback() must return null", ucE.getCallback()); - } - - /** - * javax.security.auth.callback.UnsupportedCallbackExceptionTest#UnsupportedCallbackException(Callback callback) - * javax.security.auth.callback.UnsupportedCallbackExceptionTest#getCallback() - * Assertion: constructs with not null parameter. - */ - public void testUnsupportedCallbackException02() { - myCallback c = new myCallback(); - assertNotNull("Callback object is null", c); - UnsupportedCallbackException ucE = new UnsupportedCallbackException(c); - assertNull("getMessage() must return null.", ucE.getMessage()); - assertEquals("Incorrect callback object was returned", c, ucE.getCallback()); - } - - /** - * javax.security.auth.callback.UnsupportedCallbackExceptionTest#UnsupportedCallbackException(Callback callback, String msg) - * Assertion: constructs with null callback parameter and null message. - */ - public void testUnsupportedCallbackException03() { - UnsupportedCallbackException ucE = new UnsupportedCallbackException(null, null); - assertNull("getMessage() must return null.", ucE.getMessage()); - assertNull("getCallback() must return null.", ucE.getCallback()); - } - - /** - * javax.security.auth.callback.UnsupportedCallbackExceptionTest#UnsupportedCallbackException(Callback callback, String msg) - * Assertion: constructs with null callback parameter and not null message. - */ - public void testUnsupportedCallbackException04() { - UnsupportedCallbackException ucE; - for (int i = 0; i < msgs.length; i++) { - ucE = new UnsupportedCallbackException(null, msgs[i]); - assertEquals("getMessage() must return: ".concat(msgs[i]), ucE.getMessage(), msgs[i]); - assertNull("getCallback() must return null.", ucE.getCallback()); - } - } - - /** - * javax.security.auth.callback.UnsupportedCallbackExceptionTest#UnsupportedCallbackException(Callback callback, String msg) - * Assertion: constructs with not null callback parameter and null message. - */ - public void testUnsupportedCallbackException05() { - myCallback c = new myCallback(); - assertNotNull("Callback object is null", c); - UnsupportedCallbackException ucE = new UnsupportedCallbackException(c, null); - assertNull("getMessage() must return null.", ucE.getMessage()); - assertEquals("Incorrect callback object was returned", c, ucE.getCallback()); - } - - /** - * javax.security.auth.callback.UnsupportedCallbackExceptionTest#UnsupportedCallbackException(Callback callback, String msg) - * Assertion: constructs with not null parameters. - */ - public void testUnsupportedCallbackException06() { - myCallback c = new myCallback(); - assertNotNull("Callback object is null", c); - UnsupportedCallbackException ucE; - for (int i = 0; i < msgs.length; i++) { - ucE = new UnsupportedCallbackException(c, msgs[i]); - assertEquals("getMessage() must return: ".concat(msgs[i]), ucE.getMessage(), msgs[i]); - assertEquals("Incorrect callback object was returned", c, ucE.getCallback()); - } - } -} - -class myCallback implements Callback { - myCallback(){ - } -} - diff --git a/luni/src/test/java/tests/api/javax/security/auth/X500PrincipalTest.java b/luni/src/test/java/tests/api/javax/security/auth/X500PrincipalTest.java deleted file mode 100644 index 7cb81bb..0000000 --- a/luni/src/test/java/tests/api/javax/security/auth/X500PrincipalTest.java +++ /dev/null @@ -1,270 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 tests.api.javax.security.auth; - -import junit.framework.TestCase; - -import javax.security.auth.x500.X500Principal; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import org.apache.harmony.security.tests.support.cert.TestUtils; - -/** - * Tests for <code>X500Principal</code> class constructors and methods. - * - */ -public class X500PrincipalTest extends TestCase { - - /** - * javax.security.auth.x500.X500Principal#X500Principal(String name) - */ - public void test_X500Principal_01() { - String name = "CN=Duke,OU=JavaSoft,O=Sun Microsystems,C=US"; - - try { - X500Principal xpr = new X500Principal(name); - assertNotNull("Null object returned", xpr); - String resName = xpr.getName(); - assertEquals(name, resName); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - - try { - X500Principal xpr = new X500Principal((String)null); - fail("NullPointerException wasn't thrown"); - } catch (NullPointerException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of NullPointerException"); - } - - try { - X500Principal xpr = new X500Principal("X500PrincipalName"); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of IllegalArgumentException"); - } - } - - /** - * javax.security.auth.x500.X500Principal#X500Principal(InputStream is) - */ - public void test_X500Principal_02() { - String name = "CN=Duke,OU=JavaSoft,O=Sun Microsystems,C=US"; - byte[] ba = getByteArray(TestUtils.getX509Certificate_v1()); - ByteArrayInputStream is = new ByteArrayInputStream(ba); - InputStream isNull = null; - - try { - X500Principal xpr = new X500Principal(is); - assertNotNull("Null object returned", xpr); - byte[] resArray = xpr.getEncoded(); - assertEquals(ba.length, resArray.length); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - - try { - X500Principal xpr = new X500Principal(isNull); - fail("NullPointerException wasn't thrown"); - } catch (NullPointerException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of NullPointerException"); - } - - is = new ByteArrayInputStream(name.getBytes()); - try { - X500Principal xpr = new X500Principal(is); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of IllegalArgumentException"); - } - } - - /** - * javax.security.auth.x500.X500Principal#X500Principal(byte[] name) - */ - public void test_X500Principal_03() { - String name = "CN=Duke,OU=JavaSoft,O=Sun Microsystems,C=US"; - byte[] ba = getByteArray(TestUtils.getX509Certificate_v1()); - byte[] baNull = null; - - try { - X500Principal xpr = new X500Principal(ba); - assertNotNull("Null object returned", xpr); - byte[] resArray = xpr.getEncoded(); - assertEquals(ba.length, resArray.length); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - - try { - X500Principal xpr = new X500Principal(baNull); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of IllegalArgumentException"); - } - - ba = name.getBytes(); - try { - X500Principal xpr = new X500Principal(ba); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException npe) { - } catch (Exception e) { - fail(e + " was thrown instead of IllegalArgumentException"); - } - } - - /** - * javax.security.auth.x500.X500Principal#getName() - */ - public void test_getName() { - String name = "CN=Duke,OU=JavaSoft,O=Sun Microsystems,C=US"; - X500Principal xpr = new X500Principal(name); - try { - String resName = xpr.getName(); - assertEquals(name, resName); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - } - - /** - * javax.security.auth.x500.X500Principal#getName(String format) - */ - public void test_getName_Format() { - String name = "CN=Duke,OU=JavaSoft,O=Sun Microsystems,C=US"; - String expectedName = "cn=duke,ou=javasoft,o=sun microsystems,c=us"; - X500Principal xpr = new X500Principal(name); - try { - String resName = xpr.getName(X500Principal.CANONICAL); - assertEquals(expectedName, resName); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - - expectedName = "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US"; - try { - String resName = xpr.getName(X500Principal.RFC1779); - assertEquals(expectedName, resName); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - - try { - String resName = xpr.getName(X500Principal.RFC2253); - assertEquals(name, resName); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - - try { - String resName = xpr.getName(null); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iae) { - } - try { - String resName = xpr.getName("RFC2254"); - fail("IllegalArgumentException wasn't thrown"); - } catch (IllegalArgumentException iae) { - } - } - - /** - * javax.security.auth.x500.X500Principal#hashCode() - */ - public void test_hashCode() { - String name = "CN=Duke,OU=JavaSoft,O=Sun Microsystems,C=US"; - X500Principal xpr = new X500Principal(name); - try { - int res = xpr.hashCode(); - assertNotNull(res); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - } - - /** - * javax.security.auth.x500.X500Principal#toString() - */ - public void test_toString() { - String name = "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US"; - X500Principal xpr = new X500Principal(name); - try { - String res = xpr.toString(); - assertNotNull(res); - assertEquals(name, res); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - } - - /** - * javax.security.auth.x500.X500Principal#getEncoded() - */ - public void test_getEncoded() { - byte[] ba = getByteArray(TestUtils.getX509Certificate_v1()); - X500Principal xpr = new X500Principal(ba); - try { - byte[] res = xpr.getEncoded(); - assertNotNull(res); - assertEquals(ba.length, res.length); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - } - - /** - * javax.security.auth.x500.X500Principal#equals(Object o) - */ - public void test_equals() { - String name1 = "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US"; - String name2 = "cn=duke,ou=javasoft,o=sun microsystems,c=us"; - String name3 = "CN=Alex Astapchuk, OU=SSG, O=Intel ZAO, C=RU"; - X500Principal xpr1 = new X500Principal(name1); - X500Principal xpr2 = new X500Principal(name2); - X500Principal xpr3 = new X500Principal(name3); - try { - assertTrue("False returned", xpr1.equals(xpr2)); - assertFalse("True returned", xpr1.equals(xpr3)); - } catch (Exception e) { - fail("Unexpected exception: " + e); - } - } - - private byte[] getByteArray(byte[] array) { - byte[] x = null; - try { - ByteArrayInputStream is = new ByteArrayInputStream(array); - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - X509Certificate cert = (X509Certificate)cf.generateCertificate(is); - X500Principal xx = cert.getIssuerX500Principal(); - x = xx.getEncoded(); - } catch (Exception e) { - return null; - } - return x; - } -} - diff --git a/luni/src/test/java/tests/api/javax/security/cert/CertificateEncodingExceptionTest.java b/luni/src/test/java/tests/api/javax/security/cert/CertificateEncodingExceptionTest.java deleted file mode 100644 index 53fbd9f..0000000 --- a/luni/src/test/java/tests/api/javax/security/cert/CertificateEncodingExceptionTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -/** -* @author Vera Y. Petrashkova -* @version $Revision$ -*/ - -package tests.api.javax.security.cert; - -import junit.framework.TestCase; - -import javax.security.cert.CertificateEncodingException; - -/** - * Tests for <code>DigestException</code> class constructors and methods. - * - */ -public class CertificateEncodingExceptionTest extends TestCase { - - static String[] msgs = { - "", - "Check new message", - "Check new message Check new message Check new message Check new message Check new message" }; - - static Throwable tCause = new Throwable("Throwable for exception"); - - /** - * Test for <code>CertificateEncodingException()</code> constructor - * Assertion: constructs CertificateEncodingException with no detail message - */ - public void testCertificateEncodingException01() { - CertificateEncodingException tE = new CertificateEncodingException(); - assertNull("getMessage() must return null.", tE.getMessage()); - assertNull("getCause() must return null", tE.getCause()); - } - - /** - * Test for <code>CertificateEncodingException(String)</code> constructor - * Assertion: constructs CertificateEncodingException with detail message - * msg. Parameter <code>msg</code> is not null. - */ - public void testCertificateEncodingException02() { - CertificateEncodingException tE; - for (int i = 0; i < msgs.length; i++) { - tE = new CertificateEncodingException(msgs[i]); - assertEquals("getMessage() must return: ".concat(msgs[i]), tE - .getMessage(), msgs[i]); - assertNull("getCause() must return null", tE.getCause()); - } - } - - /** - * Test for <code>CertificateEncodingException(String)</code> constructor - * Assertion: constructs CertificateEncodingException when <code>msg</code> - * is null - */ - public void testCertificateEncodingException03() { - String msg = null; - CertificateEncodingException tE = new CertificateEncodingException(msg); - assertNull("getMessage() must return null.", tE.getMessage()); - assertNull("getCause() must return null", tE.getCause()); - } -} diff --git a/luni/src/test/java/tests/api/javax/security/cert/CertificateExceptionTest.java b/luni/src/test/java/tests/api/javax/security/cert/CertificateExceptionTest.java deleted file mode 100644 index ccc3a2c..0000000 --- a/luni/src/test/java/tests/api/javax/security/cert/CertificateExceptionTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -/** -* @author Vera Y. Petrashkova -* @version $Revision$ -*/ - -package tests.api.javax.security.cert; - -import junit.framework.TestCase; - -import javax.security.cert.CertificateException; - - -/** - * Tests for <code>DigestException</code> class constructors and methods. - * - */ -public class CertificateExceptionTest extends TestCase { - - static String[] msgs = { - "", - "Check new message", - "Check new message Check new message Check new message Check new message Check new message" }; - - static Throwable tCause = new Throwable("Throwable for exception"); - - /** - * Test for <code>CertificateException()</code> constructor Assertion: - * constructs CertificateException with no detail message - */ - public void testCertificateException01() { - CertificateException tE = new CertificateException(); - assertNull("getMessage() must return null.", tE.getMessage()); - assertNull("getCause() must return null", tE.getCause()); - } - - /** - * Test for <code>CertificateException(String)</code> constructor - * Assertion: constructs CertificateException with detail message msg. - * Parameter <code>msg</code> is not null. - */ - public void testCertificateException02() { - CertificateException tE; - for (int i = 0; i < msgs.length; i++) { - tE = new CertificateException(msgs[i]); - assertEquals("getMessage() must return: ".concat(msgs[i]), tE - .getMessage(), msgs[i]); - assertNull("getCause() must return null", tE.getCause()); - } - } - - /** - * Test for <code>CertificateException(String)</code> constructor - * Assertion: constructs CertificateException when <code>msg</code> is - * null - */ - public void testCertificateException03() { - String msg = null; - CertificateException tE = new CertificateException(msg); - assertNull("getMessage() must return null.", tE.getMessage()); - assertNull("getCause() must return null", tE.getCause()); - } -} diff --git a/luni/src/test/java/tests/api/javax/security/cert/CertificateExpiredExceptionTest.java b/luni/src/test/java/tests/api/javax/security/cert/CertificateExpiredExceptionTest.java deleted file mode 100644 index d0e94e3..0000000 --- a/luni/src/test/java/tests/api/javax/security/cert/CertificateExpiredExceptionTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -/** -* @author Vera Y. Petrashkova -* @version $Revision$ -*/ - -package tests.api.javax.security.cert; - -import junit.framework.TestCase; - -import javax.security.cert.CertificateExpiredException; - - -/** - * Tests for <code>DigestException</code> class constructors and methods. - * - */ -public class CertificateExpiredExceptionTest extends TestCase { - - static String[] msgs = { - "", - "Check new message", - "Check new message Check new message Check new message Check new message Check new message" }; - - static Throwable tCause = new Throwable("Throwable for exception"); - - /** - * Test for <code>CertificateExpiredException()</code> constructor - * Assertion: constructs CertificateExpiredException with no detail message - */ - public void testCertificateExpiredException01() { - CertificateExpiredException tE = new CertificateExpiredException(); - assertNull("getMessage() must return null.", tE.getMessage()); - assertNull("getCause() must return null", tE.getCause()); - } - - /** - * Test for <code>CertificateExpiredException(String)</code> constructor - * Assertion: constructs CertificateExpiredException with detail message - * msg. Parameter <code>msg</code> is not null. - */ - public void testCertificateExpiredException02() { - CertificateExpiredException tE; - for (int i = 0; i < msgs.length; i++) { - tE = new CertificateExpiredException(msgs[i]); - assertEquals("getMessage() must return: ".concat(msgs[i]), tE - .getMessage(), msgs[i]); - assertNull("getCause() must return null", tE.getCause()); - } - } - - /** - * Test for <code>CertificateExpiredException(String)</code> constructor - * Assertion: constructs CertificateExpiredException when <code>msg</code> - * is null - */ - public void testCertificateExpiredException03() { - String msg = null; - CertificateExpiredException tE = new CertificateExpiredException(msg); - assertNull("getMessage() must return null.", tE.getMessage()); - assertNull("getCause() must return null", tE.getCause()); - } -} diff --git a/luni/src/test/java/tests/api/javax/security/cert/CertificateNotYetValidExceptionTest.java b/luni/src/test/java/tests/api/javax/security/cert/CertificateNotYetValidExceptionTest.java deleted file mode 100644 index c746648..0000000 --- a/luni/src/test/java/tests/api/javax/security/cert/CertificateNotYetValidExceptionTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -/** -* @author Vera Y. Petrashkova -* @version $Revision$ -*/ - -package tests.api.javax.security.cert; - -import junit.framework.TestCase; - -import javax.security.cert.CertificateNotYetValidException; - - -/** - * Tests for <code>DigestException</code> class constructors and methods. - * - */ -public class CertificateNotYetValidExceptionTest extends TestCase { - - static String[] msgs = { - "", - "Check new message", - "Check new message Check new message Check new message Check new message Check new message" }; - - static Throwable tCause = new Throwable("Throwable for exception"); - - /** - * Test for <code>CertificateNotYetValidException()</code> constructor - * Assertion: constructs CertificateNotYetValidException with no detail - * message - */ - public void testCertificateNotYetValidException01() { - CertificateNotYetValidException tE = new CertificateNotYetValidException(); - assertNull("getMessage() must return null.", tE.getMessage()); - assertNull("getCause() must return null", tE.getCause()); - } - - /** - * Test for <code>CertificateNotYetValidException(String)</code> - * constructor Assertion: constructs CertificateNotYetValidException with - * detail message msg. Parameter <code>msg</code> is not null. - */ - public void testCertificateNotYetValidException02() { - CertificateNotYetValidException tE; - for (int i = 0; i < msgs.length; i++) { - tE = new CertificateNotYetValidException(msgs[i]); - assertEquals("getMessage() must return: ".concat(msgs[i]), tE - .getMessage(), msgs[i]); - assertNull("getCause() must return null", tE.getCause()); - } - } - - /** - * Test for <code>CertificateNotYetValidException(String)</code> - * constructor Assertion: constructs CertificateNotYetValidException when - * <code>msg</code> is null - */ - public void testCertificateNotYetValidException03() { - String msg = null; - CertificateNotYetValidException tE = new CertificateNotYetValidException( - msg); - assertNull("getMessage() must return null.", tE.getMessage()); - assertNull("getCause() must return null", tE.getCause()); - } -} diff --git a/luni/src/test/java/tests/api/javax/security/cert/CertificateParsingExceptionTest.java b/luni/src/test/java/tests/api/javax/security/cert/CertificateParsingExceptionTest.java deleted file mode 100644 index bc07ff6..0000000 --- a/luni/src/test/java/tests/api/javax/security/cert/CertificateParsingExceptionTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -/** -* @author Vera Y. Petrashkova -* @version $Revision$ -*/ - -package tests.api.javax.security.cert; - -import junit.framework.TestCase; - -import javax.security.cert.CertificateParsingException; - - -/** - * Tests for <code>DigestException</code> class constructors and methods. - * - */ -public class CertificateParsingExceptionTest extends TestCase { - - - static String[] msgs = { - "", - "Check new message", - "Check new message Check new message Check new message Check new message Check new message" }; - - static Throwable tCause = new Throwable("Throwable for exception"); - - /** - * Test for <code>CertificateParsingException()</code> constructor - * Assertion: constructs CertificateParsingException with no detail message - */ - public void testCertificateParsingException01() { - CertificateParsingException tE = new CertificateParsingException(); - assertNull("getMessage() must return null.", tE.getMessage()); - assertNull("getCause() must return null", tE.getCause()); - } - - /** - * Test for <code>CertificateParsingException(String)</code> constructor - * Assertion: constructs CertificateParsingException with detail message - * msg. Parameter <code>msg</code> is not null. - */ - public void testCertificateParsingException02() { - CertificateParsingException tE; - for (int i = 0; i < msgs.length; i++) { - tE = new CertificateParsingException(msgs[i]); - assertEquals("getMessage() must return: ".concat(msgs[i]), tE - .getMessage(), msgs[i]); - assertNull("getCause() must return null", tE.getCause()); - } - } - - /** - * Test for <code>CertificateParsingException(String)</code> constructor - * Assertion: constructs CertificateParsingException when <code>msg</code> - * is null - */ - public void testCertificateParsingException03() { - String msg = null; - CertificateParsingException tE = new CertificateParsingException(msg); - assertNull("getMessage() must return null.", tE.getMessage()); - assertNull("getCause() must return null", tE.getCause()); - } -} diff --git a/luni/src/test/java/tests/api/javax/security/cert/CertificateTest.java b/luni/src/test/java/tests/api/javax/security/cert/CertificateTest.java deleted file mode 100644 index da1c7a0..0000000 --- a/luni/src/test/java/tests/api/javax/security/cert/CertificateTest.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -/** - * @author Alexander Y. Kleymenov - * @version $Revision$ - */ - -package tests.api.javax.security.cert; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PublicKey; -import java.security.SignatureException; - -import javax.security.cert.Certificate; -import javax.security.cert.CertificateEncodingException; -import javax.security.cert.CertificateException; - -public class CertificateTest extends TestCase { - - /** - * The stub class used for testing of non abstract methods. - */ - private class TBTCert extends Certificate { - public byte[] getEncoded() throws CertificateEncodingException { - return null; - } - - public void verify(PublicKey key) throws CertificateException, - NoSuchAlgorithmException, InvalidKeyException, - NoSuchProviderException, SignatureException { - } - - public void verify(PublicKey key, String sigProvider) - throws CertificateException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, - SignatureException { - } - - public String toString() { - return "TBTCert"; - } - - public PublicKey getPublicKey() { - return null; - } - } - - /** - * Test for <code>Certificate()</code> constructor<br> - */ - public final void testCertificate() { - TBTCert tbt_cert = new TBTCert(); - - assertNull("Public key should be null", tbt_cert.getPublicKey()); - assertEquals("Wrong string representation for Certificate", "TBTCert", tbt_cert.toString()); - } - - /** - * equals(Object obj) method testing. Tests the correctness of equal - * operation: it should be reflexive, symmetric, transitive, consistent and - * should be false on null object. - */ - public void testEquals() { - TBTCert tbt_cert = new TBTCert() { - public byte[] getEncoded() { - return new byte[] { 1, 2, 3 }; - } - }; - - TBTCert tbt_cert_1 = new TBTCert() { - public byte[] getEncoded() { - return new byte[] { 1, 2, 3 }; - } - }; - - TBTCert tbt_cert_2 = new TBTCert() { - public byte[] getEncoded() { - return new byte[] { 1, 2, 3 }; - } - }; - - TBTCert tbt_cert_3 = new TBTCert() { - public byte[] getEncoded() { - return new byte[] { 3, 2, 1 }; - } - }; - - // checking for reflexive law: - assertTrue("The equivalence relation should be reflexive.", tbt_cert - .equals(tbt_cert)); - - assertEquals( - "The Certificates with equal encoded form should be equal", - tbt_cert, tbt_cert_1); - // checking for symmetric law: - assertTrue("The equivalence relation should be symmetric.", tbt_cert_1 - .equals(tbt_cert)); - - assertEquals( - "The Certificates with equal encoded form should be equal", - tbt_cert_1, tbt_cert_2); - // checking for transitive law: - assertTrue("The equivalence relation should be transitive.", tbt_cert - .equals(tbt_cert_2)); - - assertFalse("Should not be equal to null object.", tbt_cert - .equals(null)); - - assertFalse("The Certificates with differing encoded form " - + "should not be equal", tbt_cert.equals(tbt_cert_3)); - assertFalse("The Certificates should not be equals to the object " - + "which is not an instance of Certificate", tbt_cert - .equals(new Object())); - } - - /** - * hashCode() method testing. - */ - public void testHashCode() { - TBTCert tbt_cert = new TBTCert() { - public byte[] getEncoded() { - return new byte[] { 1, 2, 3 }; - } - }; - TBTCert tbt_cert_1 = new TBTCert() { - public byte[] getEncoded() { - return new byte[] { 1, 2, 3 }; - } - }; - - assertTrue("Equal objects should have the same hash codes.", tbt_cert - .hashCode() == tbt_cert_1.hashCode()); - } - - public static Test suite() { - return new TestSuite(CertificateTest.class); - } -} diff --git a/luni/src/test/java/tests/api/javax/security/cert/X509CertificateTest.java b/luni/src/test/java/tests/api/javax/security/cert/X509CertificateTest.java deleted file mode 100644 index e937db9..0000000 --- a/luni/src/test/java/tests/api/javax/security/cert/X509CertificateTest.java +++ /dev/null @@ -1,788 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -/** - * @author Alexander Y. Kleymenov - * @version $Revision$ - */ - -package tests.api.javax.security.cert; - -import dalvik.annotation.BrokenTest; -import dalvik.annotation.SideEffect; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -import tests.targets.security.cert.CertificateFactoryTestX509; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Principal; -import java.security.Provider; -import java.security.PublicKey; -import java.security.Security; -import java.security.SignatureException; -import java.security.Provider.Service; -import java.security.cert.CertificateFactory; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.Set; -import java.util.logging.Logger; - -import javax.security.cert.Certificate; -import javax.security.cert.CertificateEncodingException; -import javax.security.cert.CertificateException; -import javax.security.cert.CertificateExpiredException; -import javax.security.cert.CertificateNotYetValidException; -import javax.security.cert.X509Certificate; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; -import tests.targets.security.cert.CertificateFactoryTestX509; - -/** - */ -public class X509CertificateTest extends TestCase { - - // Testing data was generated by using of classes - // from org.apache.harmony.security.asn1 package encoded - // by org.apache.harmony.misc.Base64 class. - - private static String base64cert = "-----BEGIN CERTIFICATE-----\n" - + "MIIC+jCCAragAwIBAgICAiswDAYHKoZIzjgEAwEBADAdMRswGQYDVQQKExJDZXJ0a" - + "WZpY2F0ZSBJc3N1ZXIwIhgPMTk3MDAxMTIxMzQ2NDBaGA8xOTcwMDEyNDAzMzMyMF" - + "owHzEdMBsGA1UEChMUU3ViamVjdCBPcmdhbml6YXRpb24wGTAMBgcqhkjOOAQDAQE" - + "AAwkAAQIDBAUGBwiBAgCqggIAVaOCAhQwggIQMA8GA1UdDwEB/wQFAwMBqoAwEgYD" - + "VR0TAQH/BAgwBgEB/wIBBTAUBgNVHSABAf8ECjAIMAYGBFUdIAAwZwYDVR0RAQH/B" - + "F0wW4EMcmZjQDgyMi5OYW1lggdkTlNOYW1lpBcxFTATBgNVBAoTDE9yZ2FuaXphdG" - + "lvboYaaHR0cDovL3VuaWZvcm0uUmVzb3VyY2UuSWSHBP///wCIByoDolyDsgMwDAY" - + "DVR0eAQH/BAIwADAMBgNVHSQBAf8EAjAAMIGZBgNVHSUBAf8EgY4wgYsGBFUdJQAG" - + "CCsGAQUFBwMBBggrBgEFBQcDAQYIKwYBBQUHAwIGCCsGAQUFBwMDBggrBgEFBQcDB" - + "AYIKwYBBQUHAwUGCCsGAQUFBwMGBggrBgEFBQcDBwYIKwYBBQUHAwgGCCsGAQUFBw" - + "MJBggrBgEFBQgCAgYKKwYBBAGCNwoDAwYJYIZIAYb4QgQBMA0GA1UdNgEB/wQDAgE" - + "BMA4GBCpNhgkBAf8EAwEBATBkBgNVHRIEXTBbgQxyZmNAODIyLk5hbWWCB2ROU05h" - + "bWWkFzEVMBMGA1UEChMMT3JnYW5pemF0aW9uhhpodHRwOi8vdW5pZm9ybS5SZXNvd" - + "XJjZS5JZIcE////AIgHKgOiXIOyAzAJBgNVHR8EAjAAMAoGA1UdIwQDAQEBMAoGA1" - + "UdDgQDAQEBMAoGA1UdIQQDAQEBMAwGByqGSM44BAMBAQADMAAwLQIUAL4QvoazNWP" - + "7jrj84/GZlhm09DsCFQCBKGKCGbrP64VtUt4JPmLjW1VxQA==\n" - + "-----END CERTIFICATE-----"; - - /* - * a self-signed certificate - */ - private static final String selfSignedCert = "-----BEGIN CERTIFICATE-----\n" + - "MIIDPzCCAqigAwIBAgIBADANBgkqhkiG9w0BAQUFADB5MQswCQYDVQQGEwJBTjEQ" + - "MA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5k" + - "cm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBh" + - "bmRyb2lkLmNvbTAeFw0wOTAzMjAxNzAwMDZaFw0xMjAzMTkxNzAwMDZaMHkxCzAJ" + - "BgNVBAYTAkFOMRAwDgYDVQQIEwdBbmRyb2lkMRAwDgYDVQQKEwdBbmRyb2lkMRAw" + - "DgYDVQQLEwdBbmRyb2lkMRAwDgYDVQQDEwdBbmRyb2lkMSIwIAYJKoZIhvcNAQkB" + - "FhNhbmRyb2lkQGFuZHJvaWQuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB" + - "gQCqQkDtkiEXmV8O5EK4y2Y9YyoWNDx70z4fqD+9muuzJGuM5NovMbxhBycuKHF3" + - "WK60iXzrsAYkB1c8VHHbcUEFqz2fBdLKyxy/nYohlo8TYSVpEjt3vfc0sgmp4FKU" + - "RDHO2z3rZPHWysV9L9ZvjeQpiwaYipU9epdBmvFmxQmCDQIDAQABo4HWMIHTMB0G" + - "A1UdDgQWBBTnm32QKeqQC38IQXZOQSPoQyypAzCBowYDVR0jBIGbMIGYgBTnm32Q" + - "KeqQC38IQXZOQSPoQyypA6F9pHsweTELMAkGA1UEBhMCQU4xEDAOBgNVBAgTB0Fu" + - "ZHJvaWQxEDAOBgNVBAoTB0FuZHJvaWQxEDAOBgNVBAsTB0FuZHJvaWQxEDAOBgNV" + - "BAMTB0FuZHJvaWQxIjAgBgkqhkiG9w0BCQEWE2FuZHJvaWRAYW5kcm9pZC5jb22C" + - "AQAwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOBgQAUmDApQu+r5rglS1WF" + - "BKXE3R2LasFvbBwdw2E0MAc0TWqLVW91VW4VWMX4r+C+c7rZpYXXtRqFRCuI/czL" + - "0e1GaUP/Wa6bXBcm2u7Iv2dVAaAOELmFSVTZeR57Lm9lT9kQLp24kmNndIsiDW3T" + - "XZ4pY/k2kxungOKx8b8pGYE9Bw==\n" + - "-----END CERTIFICATE-----"; - - private java.security.cert.X509Certificate cert; - - private javax.security.cert.X509Certificate tbt_cert; - - private java.security.cert.X509Certificate javaCert; - - private Provider myProvider; - - private javax.security.cert.X509Certificate javaxCert; - - private java.security.cert.Certificate javaSSCert; - - private Provider mySSProvider; - - private Certificate javaxSSCert; - - @Override - protected void setUp() throws Exception { - try { - ByteArrayInputStream bais = new ByteArrayInputStream(base64cert - .getBytes()); - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - this.cert = (java.security.cert.X509Certificate) cf - .generateCertificate(bais); - this.tbt_cert = X509Certificate.getInstance(cert.getEncoded()); - - // non self signed cert - this.javaCert = (java.security.cert.X509Certificate)cf - .generateCertificate(new ByteArrayInputStream(selfSignedCert.getBytes())); - this.javaxCert = X509Certificate.getInstance(javaCert.getEncoded()); - myProvider = cf.getProvider(); - Security.addProvider(myProvider); - - // self signed cert - this.javaSSCert = cf.generateCertificate(new ByteArrayInputStream( - selfSignedCert.getBytes())); - this.javaxSSCert = X509Certificate.getInstance(javaCert - .getEncoded()); - mySSProvider = cf.getProvider(); - Security.addProvider(mySSProvider); - - } catch (java.security.cert.CertificateException e) { - // The requested certificate type is not available. - // Test pass.. - this.cert = null; - Logger.global.warning("Error in test setup: Certificate type not supported"); - } catch (javax.security.cert.CertificateException e) { - // The requested certificate type is not available. - // Test pass.. - this.cert = null; - Logger.global.warning("Error in test setup: Certificate type not supported"); - } - } - - /** - * X509Certificate() constructor testing. - * {@link X509Certificate#X509Certificate() } - */ - public void testConstructor() { - //Direct constructor, check if it throws an exception - X509Certificate cert = new MyCertificate(); - } - - /** - * getInstance(InputStream inStream) method testing. - */ - public void testGetInstance1() { - if (this.cert == null) { - // The requested certificate type is not available. - // Test can not be applied. - return; - } - try { - ByteArrayInputStream bais = new ByteArrayInputStream(cert - .getEncoded()); - - X509Certificate.getInstance(bais); - } catch (java.security.cert.CertificateEncodingException e) { - fail("Unexpected CertificateEncodingException was thrown."); - } catch (CertificateEncodingException e) { - fail("Unexpected CertificateEncodingException was thrown."); - } catch (CertificateException e) { - // The requested certificate type is not available. - // Test pass.. - } - - // Regression for HARMONY-756 - try { - X509Certificate.getInstance((InputStream) null); - fail("No expected CertificateException"); - } catch (CertificateException e) { - // expected; - } - } - - /** - * getInstance(byte[] certData) method testing. - * @throws CertificateEncodingException - * @throws java.security.cert.CertificateEncodingException - */ - public void testGetInstance2() throws java.security.cert.CertificateEncodingException, CertificateEncodingException { - boolean certificateException = false; - X509Certificate c = null; - if (this.cert == null) { - // The requested certificate type is not available. - // Test can not be applied. - return; - } - try { - c = X509Certificate.getInstance(cert.getEncoded()); - } catch (java.security.cert.CertificateEncodingException e) { - fail("Unexpected CertificateEncodingException was thrown."); - } catch (CertificateException e) { - // The requested certificate type is not available. - // Test pass.. - certificateException = true; - - } - - if (! certificateException) { - assertNotNull(c); - assertTrue(Arrays.equals(c.getEncoded(),cert.getEncoded() )); - } - - try { - X509Certificate.getInstance(new byte[]{(byte) 1 }); - } catch (CertificateException e) { - //ok - } - - // Regression for HARMONY-756 - try { - X509Certificate.getInstance((byte[]) null); - fail("No expected CertificateException"); - } catch (CertificateException e) { - // expected; - } - - } - - /** - * checkValidity() method testing. - * @throws CertificateNotYetValidException - * @throws CertificateExpiredException - * @throws java.security.cert.CertificateExpiredException - * @throws java.security.cert.CertificateNotYetValidException - */ - public void testCheckValidity1() throws CertificateExpiredException, CertificateNotYetValidException, java.security.cert.CertificateExpiredException, java.security.cert.CertificateNotYetValidException { - if (this.cert == null) { - // The requested certificate type is not available. - // Test can not be applied. - return; - } - Date date = new Date(); - Date nb_date = tbt_cert.getNotBefore(); - Date na_date = tbt_cert.getNotAfter(); - try { - tbt_cert.checkValidity(); - assertFalse("CertificateExpiredException expected", date - .compareTo(na_date) > 0); - assertFalse("CertificateNotYetValidException expected", date - .compareTo(nb_date) < 0); - } catch (CertificateExpiredException e) { - assertTrue("Unexpected CertificateExpiredException was thrown", - date.compareTo(na_date) > 0); - } catch (CertificateNotYetValidException e) { - assertTrue("Unexpected CertificateNotYetValidException was thrown", - date.compareTo(nb_date) < 0); - } - - try { - tbt_cert.checkValidity(); - } catch (CertificateExpiredException e) { - // ok - } - - try { - cert.checkValidity(); - } catch (java.security.cert.CertificateExpiredException e) { - // ok - } - - } - - /** - * checkValidity(Date date) method testing. - * @throws CertificateNotYetValidException - * @throws CertificateExpiredException - */ - public void testCheckValidity2() throws CertificateNotYetValidException, CertificateExpiredException { - if (this.cert == null) { - // The requested certificate type is not available. - // Test can not be applied. - return; - } - Date[] date = new Date[8]; - Calendar calendar = Calendar.getInstance(); - for (int i = 0; i < date.length; i++) { - calendar.set(i * 500, Calendar.JANUARY, 1); - date[i] = calendar.getTime(); - } - Date nb_date = tbt_cert.getNotBefore(); - Date na_date = tbt_cert.getNotAfter(); - for (int i = 0; i < date.length; i++) { - try { - tbt_cert.checkValidity(date[i]); - assertFalse("CertificateExpiredException expected", date[i] - .compareTo(na_date) > 0); - assertFalse("CertificateNotYetValidException expected", date[i] - .compareTo(nb_date) < 0); - } catch (CertificateExpiredException e) { - assertTrue("Unexpected CertificateExpiredException was thrown", - date[i].compareTo(na_date) > 0); - } catch (CertificateNotYetValidException e) { - assertTrue("Unexpected CertificateNotYetValidException " - + "was thrown", date[i].compareTo(nb_date) < 0); - } - } - - Calendar calendarNow = Calendar.getInstance(); - - try { - tbt_cert.checkValidity(calendarNow.getTime()); - } catch (CertificateExpiredException e) { - //ok - } - - Calendar calendarPast = GregorianCalendar.getInstance(); - calendarPast.clear(); - - try { - tbt_cert.checkValidity(calendarPast.getTime()); - } catch (CertificateNotYetValidException e) { - //ok - } - - } - - /** - * getVersion() method testing. - */ - public void testGetVersion() { - if (this.cert == null) { - // The requested certificate type is not available. - // Test can not be applied. - return; - } - assertEquals("The version is not correct.", tbt_cert.getVersion(), 2); - } - - /** - * getSerialNumber() method testing. - */ - public void testGetSerialNumber() { - if (this.cert == null) { - // The requested certificate type is not available. - // Test can not be applied. - return; - } - assertEquals("The serial number is not correct.", tbt_cert - .getSerialNumber(), cert.getSerialNumber()); - } - - /** - * getIssuerDN() method testing. - */ - public void testGetIssuerDN() { - if (this.cert == null) { - // The requested certificate type is not available. - // Test can not be applied. - Logger.global.warning("testGetIssuerDN: error in test setup."); - } - assertEquals("The issuer DN is not correct.", tbt_cert.getIssuerDN(), - cert.getIssuerDN()); - } - - /** - * getSubjectDN() method testing. - */ - public void testGetSubjectDN() { - if (this.cert == null) { - // The requested certificate type is not available. - // Test can not be applied. - return; - } - assertEquals("The subject DN is not correct.", tbt_cert.getSubjectDN(), - cert.getSubjectDN()); - } - - /** - * getNotBefore() method testing. - */ - public void testGetNotBefore() { - if (this.cert == null) { - // The requested certificate type is not available. - // Test can not be applied. - return; - } - assertEquals("The NotBefore date is not correct.", tbt_cert - .getNotBefore(), cert.getNotBefore()); - } - - /** - * getNotAfter() method testing. - */ - public void testGetNotAfter() { - if (this.cert == null) { - // The requested certificate type is not available. - // Test can not be applied. - return; - } - assertEquals("The NotAfter date is not correct.", tbt_cert - .getNotAfter(), cert.getNotAfter()); - } - - /** - * getSigAlgName() method testing. - */ - public void testGetSigAlgName() { - if (this.cert == null) { - // The requested certificate type is not available. - // Test can not be applied. - return; - } - assertEquals("The name of signature algorithm is not correct.", - tbt_cert.getSigAlgName(), cert.getSigAlgName()); - } - - /** - * getSigAlgOID() method testing. - */ - public void testGetSigAlgOID() { - if (this.cert == null) { - // The requested certificate type is not available. - // Test can not be applied. - return; - } - assertEquals("The name of OID of signature algorithm is not correct.", - tbt_cert.getSigAlgOID(), cert.getSigAlgOID()); - } - - /** - * getSigAlgParams() method testing. - */ - public void testGetSigAlgParams() { - if (this.cert == null) { - // The requested certificate type is not available. - // Test can not be applied. - return; - } - assertTrue("The byte array with encoded algorithm parameters " - + "is not correct.", Arrays.equals(tbt_cert.getSigAlgParams(), - cert.getSigAlgParams())); - } - - /** - * The stub class used for testing of non abstract methods. - */ - private class MyCertificate extends X509Certificate { - - public MyCertificate() { - super(); - } - - @Override - public void checkValidity() throws CertificateExpiredException, - CertificateNotYetValidException { - } - - @Override - public void checkValidity(Date arg0) - throws CertificateExpiredException, - CertificateNotYetValidException { - } - - @Override - public Principal getIssuerDN() { - return null; - } - - @Override - public Date getNotAfter() { - return null; - } - - @Override - public Date getNotBefore() { - return null; - } - - @Override - public BigInteger getSerialNumber() { - return null; - } - - @Override - public String getSigAlgName() { - return null; - } - - @Override - public String getSigAlgOID() { - return null; - } - - @Override - public byte[] getSigAlgParams() { - return null; - } - - @Override - public Principal getSubjectDN() { - return null; - } - - @Override - public int getVersion() { - return 0; - } - - @Override - public byte[] getEncoded() throws CertificateEncodingException { - return null; - } - - @Override - public PublicKey getPublicKey() { - return null; - } - - @Override - public String toString() { - return null; - } - - @Override - public void verify(PublicKey key) throws CertificateException, - NoSuchAlgorithmException, InvalidKeyException, - NoSuchProviderException, SignatureException { - } - - @Override - public void verify(PublicKey key, String sigProvider) - throws CertificateException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, - SignatureException { - } - } - - public class MyModifiablePublicKey implements PublicKey { - - private PublicKey key; - private boolean modifiedAlgo; - private String algo; - private String format; - private boolean modifiedFormat; - private boolean modifiedEncoding; - private byte[] encoding; - - public MyModifiablePublicKey(PublicKey k) { - super(); - this.key = k; - } - - public String getAlgorithm() { - if (modifiedAlgo) { - return algo; - } else { - return key.getAlgorithm(); - } - } - - public String getFormat() { - if (modifiedFormat) { - return this.format; - } else { - return key.getFormat(); - } - - } - - public byte[] getEncoded() { - if (modifiedEncoding) { - return this.encoding; - } else { - return key.getEncoded(); - } - - } - - public long getSerVerUID() { - return key.serialVersionUID; - } - - public void setAlgorithm(String myAlgo) { - modifiedAlgo = true; - this.algo = myAlgo; - } - - public void setFormat(String myFormat) { - modifiedFormat = true; - format = myFormat; - } - - public void setEncoding(byte[] myEncoded) { - modifiedEncoding = true; - encoding = myEncoded; - } - } - - /** - * @throws CertificateEncodingException - * {@link Certificate#getEncoded()} - */ - public void testGetEncoded() - throws CertificateEncodingException, java.security.cert.CertificateException { - // cert = DER encoding of the ASN1.0 structure - assertTrue(Arrays.equals(cert.getEncoded(), tbt_cert.getEncoded())); - assertFalse(Arrays.equals(javaxCert.getEncoded(), tbt_cert.getEncoded())); - } - - /** - * {@link Certificate#getPublicKey()} - */ - public void testGetPublicKey() { - PublicKey key = javaxCert.getPublicKey(); - assertNotNull(key); - assertEquals(javaxCert.getPublicKey(), javaCert.getPublicKey()); - assertEquals(key.getAlgorithm(),"RSA"); - - key = javaxSSCert.getPublicKey(); - assertNotNull(key); - assertEquals(key.getAlgorithm(),"RSA"); - - //assertTrue(mySSProvider.containsKey(key)); - - } - - /** - * @throws SignatureException - * @throws NoSuchProviderException - * @throws NoSuchAlgorithmException - * @throws InvalidKeyException - * @throws CertificateException - * {@link Certificate#verify(PublicKey)} - */ - @SideEffect("Destroys MD5 provider, hurts succeeding tests") - public void testVerifyPublicKey() throws InvalidKeyException, - NoSuchAlgorithmException, NoSuchProviderException, - SignatureException, CertificateException { - - // Preconditions - assertNotNull(javaxCert.getPublicKey()); - assertNotNull(javaxSSCert.getPublicKey()); - //precondition for self signed certificates - /*assertEquals(((X509Certificate) javaxSSCert).getIssuerDN().getName(), - ((X509Certificate) javaxSSCert).getSubjectDN());*/ - - // must always evaluate true for self signed - // here not self signed: - try { - javaxCert.verify(javaxCert.getPublicKey()); - } catch (SignatureException e) { - // ok - } - - PublicKey k = javaxCert.getPublicKey(); - - MyModifiablePublicKey changedEncoding = new MyModifiablePublicKey(k); - changedEncoding - .setEncoding(new byte[javaxCert.getEncoded().length - 1]); - - try { - javaxCert.verify(tbt_cert.getPublicKey()); - } catch (InvalidKeyException e) { - // ok - } - - - try { - javaxCert.verify(null); - } catch (Exception e) { - // ok - } - - try { - javaxCert.verify(changedEncoding); - fail("Exception expected"); - } catch (Exception e) { - // ok - } - - // following test doesn't work because the algorithm is derived from - // somewhere else. - - // MyModifiablePublicKey changedAlgo = new MyModifiablePublicKey(k); - // changedAlgo.setAlgorithm("MD5withBla"); - - // try { - // javaxCert.verify(changedAlgo); - // fail("Exception expected"); - // } catch (SignatureException e) { - // // ok - // } - - // Security.removeProvider(mySSProvider.getName()); - - // try { - // javaxSSCert.verify(javaxSSCert.getPublicKey()); - // } catch (NoSuchProviderException e) { - // // ok - // } - - // Security.addProvider(mySSProvider); - - // must always evaluate true for self signed - // javaxSSCert.verify(javaxSSCert.getPublicKey()); - } - - /** - * @throws SignatureException - * @throws NoSuchProviderException - * @throws NoSuchAlgorithmException - * @throws java.security.cert.CertificateException - * @throws InvalidKeyException - * @throws IOException - * @throws CertificateException - * {@link Certificate#verify(PublicKey, String)} - */ - @SideEffect("Destroys MD5 provider, hurts succeeding tests") - public void testVerifyPublicKeyString() throws InvalidKeyException, - java.security.cert.CertificateException, NoSuchAlgorithmException, - NoSuchProviderException, SignatureException, IOException, - CertificateException { - - try { - javaxCert.verify(javaxCert.getPublicKey(), myProvider.getName()); - } catch (NoSuchAlgorithmException e) { - // ok - } - - // myProvider.getService(type, algorithm) - - Security.removeProvider(myProvider.getName()); - try { - javaxCert.verify(javaxCert.getPublicKey(), myProvider.getName()); - } catch (NoSuchProviderException e) { - // ok - } - Security.addProvider(myProvider); - - Provider[] providers = Security.getProviders("Signature.MD5withRSA"); - if (providers == null || providers.length == 0) { - fail("no Provider for Signature.MD5withRSA"); - return; - } - - // self signed cert: should verify with provider - try { - javaxSSCert.verify(javaxSSCert.getPublicKey(), - providers[0].getName()); - } catch (SignatureException e) { - fail("blu"); - } - - } - - public static Test suite() { - return new TestSuite(X509CertificateTest.class); - } -} diff --git a/luni/src/test/java/tests/api/javax/xml/parsers/DocumentBuilderFactoryTest.java b/luni/src/test/java/tests/api/javax/xml/parsers/DocumentBuilderFactoryTest.java deleted file mode 100644 index 7d79560..0000000 --- a/luni/src/test/java/tests/api/javax/xml/parsers/DocumentBuilderFactoryTest.java +++ /dev/null @@ -1,975 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.javax.xml.parsers; - -import junit.framework.TestCase; - -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.ErrorHandler; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.FactoryConfigurationError; -import javax.xml.parsers.ParserConfigurationException; - -public class DocumentBuilderFactoryTest extends TestCase { - - DocumentBuilderFactory dbf; - - List<String> cdataElements; - - List<String> textElements; - - List<String> commentElements; - - protected void setUp() throws Exception { - super.setUp(); - dbf = DocumentBuilderFactory.newInstance(); - - cdataElements = new ArrayList<String>(); - textElements = new ArrayList<String>(); - commentElements = new ArrayList<String>(); - } - - protected void tearDown() throws Exception { - dbf = null; - cdataElements = null; - textElements = null; - commentElements = null; - super.tearDown(); - } - - /** - * javax.xml.parsers.DocumentBuilderFactory#DocumentBuilderFactory(). - */ - public void test_Constructor() { - try { - new DocumentBuilderFactoryChild(); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - /** - * javax.xml.parsers.DocumentBuilderFactory#getAttribute(String). - */ -// public void test_getAttributeLjava_lang_String() { -// String[] attributes = { -// "http://java.sun.com/xml/jaxp/properties/schemaLanguage", -// "http://java.sun.com/xml/jaxp/properties/schemaSource" }; -// Object[] values = { "http://www.w3.org/2001/XMLSchema", "source" }; -// -// try { -// for (int i = 0; i < attributes.length; i++) { -// dbf.setAttribute(attributes[i], values[i]); -// assertEquals(values[i], dbf.getAttribute(attributes[i])); -// } -// } catch (IllegalArgumentException e) { -// fail("Unexpected IllegalArgumentException" + e.getMessage()); -// } catch (Exception e) { -// fail("Unexpected exception" + e.getMessage()); -// } -// -// try { -// for (int i = 0; i < attributes.length; i++) { -// dbf.setAttribute(null, null); -// fail("NullPointerException expected"); -// } -// } catch (NullPointerException e) { -// // expected -// } -// -// String[] badAttributes = {"bad1", "bad2", ""}; -// try { -// for (int i = 0; i < badAttributes.length; i++) { -// dbf.getAttribute(badAttributes[i]); -// fail("IllegalArgumentException expected"); -// } -// } catch (IllegalArgumentException e) { -// // expected -// } -// } - - /** - * javax.xml.parsers.DocumentBuilderFactory#getFeature(String). - */ -// TODO Fails on JDK. Why? -// public void test_getFeatureLjava_lang_String() { -// String[] features = { "http://xml.org/sax/features/namespaces", -// "http://xml.org/sax/features/validation", -// "http://xml.org/sax/features/external-general-entities" }; -// try { -// for (int i = 0; i < features.length; i++) { -// dbf.setFeature(features[i], true); -// assertTrue(dbf.getFeature(features[i])); -// } -// } catch (ParserConfigurationException e) { -// fail("Unexpected ParserConfigurationException " + e.getMessage()); -// } -// -// try { -// for (int i = 0; i < features.length; i++) { -// dbf.setFeature(features[i], false); -// assertFalse(dbf.getFeature(features[i])); -// } -// } catch (ParserConfigurationException e) { -// fail("Unexpected ParserConfigurationException " + e.getMessage()); -// } -// -// try { -// for (int i = 0; i < features.length; i++) { -// dbf.setFeature(null, false); -// fail("NullPointerException expected"); -// } -// } catch (NullPointerException e) { -// // expected -// } catch (ParserConfigurationException e) { -// fail("Unexpected ParserConfigurationException" + e.getMessage()); -// } -// -// String[] badFeatures = {"bad1", "bad2", ""}; -// try { -// for (int i = 0; i < badFeatures.length; i++) { -// dbf.getFeature(badFeatures[i]); -// fail("ParserConfigurationException expected"); -// } -// } catch (ParserConfigurationException e) { -// // expected -// } -// -// } - - /** - * javax.xml.parsers.DocumentBuilderFactory#getSchema(). - * TBD getSchemas() IS NOT SUPPORTED - */ -/* public void test_getSchema() { - assertNull(dbf.getSchema()); - SchemaFactory sf = - SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - try { - Schema schema = sf.newSchema(); - dbf.setSchema(schema); - assertNotNull(dbf.getSchema()); - } catch (SAXException sax) { - fail("Unexpected exception " + sax.toString()); - } - } - */ - - /** - * javax.xml.parsers.DocumentBuilderFactory#isCoalescing(). - */ - public void test_isCoalescing() { - dbf.setCoalescing(true); - assertTrue(dbf.isCoalescing()); - - dbf.setCoalescing(false); - assertFalse(dbf.isCoalescing()); - } - - /** - * javax.xml.parsers.DocumentBuilderFactory#isExpandEntityReferences(). - */ - public void test_isExpandEntityReferences() { - dbf.setExpandEntityReferences(true); - assertTrue(dbf.isExpandEntityReferences()); - - dbf.setExpandEntityReferences(false); - assertFalse(dbf.isExpandEntityReferences()); - } - - /** - * javax.xml.parsers.DocumentBuilderFactory#isIgnoringComments(). - */ - public void test_isIgnoringComments() { - dbf.setIgnoringComments(true); - assertTrue(dbf.isIgnoringComments()); - - dbf.setIgnoringComments(false); - assertFalse(dbf.isIgnoringComments()); - } - - /** - * javax.xml.parsers.DocumentBuilderFactory#isIgnoringElementContentWhitespace(). - */ - public void test_isIgnoringElementContentWhitespace() { - dbf.setIgnoringElementContentWhitespace(true); - assertTrue(dbf.isIgnoringElementContentWhitespace()); - - dbf.setIgnoringElementContentWhitespace(false); - assertFalse(dbf.isIgnoringElementContentWhitespace()); - } - - /** - * javax.xml.parsers.DocumentBuilderFactory#isNamespaceAware(). - */ - public void test_isNamespaceAware() { - dbf.setNamespaceAware(true); - assertTrue(dbf.isNamespaceAware()); - - dbf.setNamespaceAware(false); - assertFalse(dbf.isNamespaceAware()); - } - - public void test_setIsValidating() { - dbf.setValidating(true); - assertTrue(dbf.isValidating()); - - dbf.setValidating(false); - assertFalse(dbf.isValidating()); - } - - public void test_isSetXIncludeAware() { - dbf.setXIncludeAware(true); - assertTrue(dbf.isXIncludeAware()); - - dbf.setXIncludeAware(false); - assertFalse(dbf.isXIncludeAware()); - } - - /** - * javax.xml.parsers.DocumentBuilderFactory#newInstance(). - */ - public void test_newInstance() { - String className = null; - try { - // case 1: Try to obtain a new instance of factory by default. - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - assertNotNull(dbf); - - // case 2: Try to create a new instance of factory using - // property DATATYPEFACTORY_PROPERTY - className = System.getProperty("javax.xml.parsers.DocumentBuilderFactory"); - System.setProperty("javax.xml.parsers.DocumentBuilderFactory", - "org.apache.harmony.xml.parsers.DocumentBuilderFactoryImpl"); - - dbf = DocumentBuilderFactory.newInstance(); - assertNotNull(dbf); - assertTrue(dbf instanceof org.apache.harmony.xml.parsers.DocumentBuilderFactoryImpl); - - // case 3: Try to create a new instance of factory using Property - String keyValuePair = "javax.xml.parsers.DocumentBuilderFactory" - + "=" + "org.apache.harmony.xml.parsers.DocumentBuilderFactoryImpl"; - ByteArrayInputStream bis = new ByteArrayInputStream(keyValuePair - .getBytes()); - Properties prop = System.getProperties(); - prop.load(bis); - dbf = DocumentBuilderFactory.newInstance(); - assertNotNull(dbf); - assertTrue(dbf instanceof org.apache.harmony.xml.parsers.DocumentBuilderFactoryImpl); - - // case 4: Check FactoryConfiguration error - System.setProperty("javax.xml.parsers.DocumentBuilderFactory", ""); - try { - DocumentBuilderFactory.newInstance(); - } catch (FactoryConfigurationError fce) { - // expected - } - - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } finally { - // Set default value of Datatype factory, - // because of this test modifies it. - if (className == null) { - System.clearProperty("javax.xml.parsers.DocumentBuilderFactory"); - } else { - System.setProperty("javax.xml.parsers.DocumentBuilderFactory", - className); - } - } - } - - public void test_newDocumentBuilder() { - // Ordinary case - try { - DocumentBuilder db = dbf.newDocumentBuilder(); - assertTrue(db instanceof DocumentBuilder); - db.parse(getClass().getResourceAsStream("/simple.xml")); - } catch(Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - - // Exception case - dbf.setValidating(true); - try { - DocumentBuilder db = dbf.newDocumentBuilder(); - } catch(ParserConfigurationException e) { - // Expected, since Android doesn't have a validating parser. - } - } - - /** - * javax.xml.parsers.DocumentBuilderFactory#setAttribute(java.lang.String, - * java.lang.Object). - */ -// public void test_setAttributeLjava_lang_StringLjava_lang_Object() { -// String[] attributes = { -// "http://java.sun.com/xml/jaxp/properties/schemaLanguage", -// "http://java.sun.com/xml/jaxp/properties/schemaSource" }; -// Object[] values = { "http://www.w3.org/2001/XMLSchema", "source" }; -// -// try { -// for (int i = 0; i < attributes.length; i++) { -// dbf.setAttribute(attributes[i], values[i]); -// assertEquals(values[i], dbf.getAttribute(attributes[i])); -// } -// } catch (IllegalArgumentException e) { -// fail("Unexpected IllegalArgumentException" + e.getMessage()); -// } catch (Exception e) { -// fail("Unexpected exception" + e.getMessage()); -// } -// -// String[] badAttributes = {"bad1", "bad2", ""}; -// try { -// for (int i = 0; i < badAttributes.length; i++) { -// dbf.setAttribute(badAttributes[i], ""); -// fail("IllegalArgumentException expected"); -// } -// } catch (IllegalArgumentException iae) { -// // expected -// } -// -// try { -// for (int i = 0; i < attributes.length; i++) { -// dbf.setAttribute(null, null); -// fail("NullPointerException expected"); -// } -// } catch (NullPointerException e) { -// // expected -// } -// } - - /** - * javax.xml.parsers.DocumentBuilderFactory#setCoalescing(boolean). - */ - public void test_setCoalescingZ() { - dbf.setCoalescing(true); - assertTrue(dbf.isCoalescing()); - - textElements.clear(); - cdataElements.clear(); - Exception parseException = null; - DocumentBuilder parser = null; - - try { - parser = dbf.newDocumentBuilder(); - ValidationErrorHandler errorHandler = new ValidationErrorHandler(); - parser.setErrorHandler(errorHandler); - - Document document = parser.parse(getClass().getResourceAsStream( - "/recipt.xml")); - - parseException = errorHandler.getFirstException(); - - goThroughDocument((Node) document, ""); - assertTrue(textElements - .contains("BeefParmesan<title>withGarlicAngelHairPasta</title>")); - } catch (Exception ex) { - parseException = ex; - } - parser.setErrorHandler(null); - - if (parseException != null) { - fail("Unexpected exception " + parseException.getMessage()); - } - - dbf.setCoalescing(false); - assertFalse(dbf.isCoalescing()); - - textElements.clear(); - cdataElements.clear(); - - try { - parser = dbf.newDocumentBuilder(); - ValidationErrorHandler errorHandler = new ValidationErrorHandler(); - parser.setErrorHandler(errorHandler); - - Document document = parser.parse(getClass().getResourceAsStream( - "/recipt.xml")); - - parseException = errorHandler.getFirstException(); - - goThroughDocument((Node) document, ""); - - assertFalse(textElements - .contains("BeefParmesan<title>withGarlicAngelHairPasta</title>")); - - } catch (Exception ex) { - parseException = ex; - } - parser.setErrorHandler(null); - - if (parseException != null) { - fail("Unexpected exception " + parseException.getMessage()); - } - } - - /** - * javax.xml.parsers.DocumentBuilderFactory#setExpandEntityReferences(boolean). - */ - public void test_setExpandEntityReferencesZ() { - dbf.setExpandEntityReferences(true); - assertTrue(dbf.isExpandEntityReferences()); - - Exception parseException = null; - DocumentBuilder parser = null; - - try { - parser = dbf.newDocumentBuilder(); - ValidationErrorHandler errorHandler = new ValidationErrorHandler(); - parser.setErrorHandler(errorHandler); - - Document document = parser.parse(getClass().getResourceAsStream( - "/recipt.xml")); - - parseException = errorHandler.getFirstException(); - - assertNotNull(document); - - } catch (Exception ex) { - parseException = ex; - } - parser.setErrorHandler(null); - - if (parseException != null) { - fail("Unexpected exception " + parseException.getMessage()); - } - - dbf.setExpandEntityReferences(false); - assertFalse(dbf.isExpandEntityReferences()); - try { - parser = dbf.newDocumentBuilder(); - ValidationErrorHandler errorHandler = new ValidationErrorHandler(); - parser.setErrorHandler(errorHandler); - - Document document = parser.parse(getClass().getResourceAsStream( - "/recipt.xml")); - - parseException = errorHandler.getFirstException(); - - assertNotNull(document); - - } catch (Exception ex) { - parseException = ex; - } - parser.setErrorHandler(null); - - if (parseException != null) { - fail("Unexpected exception " + parseException.getMessage()); - } - } - - /** - * javax.xml.parsers.DocumentBuilderFactory#setFeature(java.lang.String). - */ - public void test_getSetFeatureLjava_lang_String() { - String[] features = { "http://xml.org/sax/features/namespaces", - "http://xml.org/sax/features/validation" }; - try { - for (int i = 0; i < features.length; i++) { - dbf.setFeature(features[i], true); - assertTrue(dbf.getFeature(features[i])); - } - } catch (ParserConfigurationException e) { - fail("Unexpected ParserConfigurationException" + e.getMessage()); - } - - try { - for (int i = 0; i < features.length; i++) { - dbf.setFeature(features[i], false); - assertFalse(dbf.getFeature(features[i])); - } - } catch (ParserConfigurationException e) { - fail("Unexpected ParserConfigurationException" + e.getMessage()); - } - - try { - for (int i = 0; i < features.length; i++) { - dbf.setFeature(null, false); - fail("NullPointerException expected"); - } - } catch (NullPointerException e) { - // expected - } catch (ParserConfigurationException e) { - fail("Unexpected ParserConfigurationException" + e.getMessage()); - } - - String[] badFeatures = { "bad1", "bad2", "" }; - try { - for (int i = 0; i < badFeatures.length; i++) { - dbf.setFeature(badFeatures[i], false); - fail("ParserConfigurationException expected"); - } - } catch (ParserConfigurationException e) { - // expected - } - } - - /** - * javax.xml.parsers.DocumentBuilderFactory#setIgnoringComments(boolean). - */ - public void test_setIgnoringCommentsZ() { - commentElements.clear(); - - dbf.setIgnoringComments(true); - assertTrue(dbf.isIgnoringComments()); - - try { - DocumentBuilder parser = dbf.newDocumentBuilder(); - - Document document = parser.parse(getClass().getResourceAsStream( - "/recipt.xml")); - - goThroughDocument((Node) document, ""); - assertFalse(commentElements.contains("comment1")); - assertFalse(commentElements.contains("comment2")); - - } catch (IOException e) { - fail("Unexpected IOException " + e.getMessage()); - } catch (ParserConfigurationException e) { - fail("Unexpected ParserConfigurationException " + e.getMessage()); - } catch (SAXException e) { - fail("Unexpected SAXException " + e.getMessage()); - } - - commentElements.clear(); - - dbf.setIgnoringComments(false); - assertFalse(dbf.isIgnoringComments()); - - try { - DocumentBuilder parser = dbf.newDocumentBuilder(); - - Document document = parser.parse(getClass().getResourceAsStream( - "/recipt.xml")); - - goThroughDocument((Node) document, ""); - assertTrue(commentElements.contains("comment1")); - assertTrue(commentElements.contains("comment2")); - - } catch (IOException e) { - fail("Unexpected IOException " + e.getMessage()); - } catch (ParserConfigurationException e) { - fail("Unexpected ParserConfigurationException " + e.getMessage()); - } catch (SAXException e) { - fail("Unexpected SAXException " + e.getMessage()); - } - } - - /** - * javax.xml.parsers.DocumentBuilderFactory#setIgnoringElementContentWhitespace(boolean). - */ - public void test_setIgnoringElementContentWhitespaceZ() { - dbf.setIgnoringElementContentWhitespace(true); - assertTrue(dbf.isIgnoringElementContentWhitespace()); - - try { - DocumentBuilder parser = dbf.newDocumentBuilder(); - - Document document = parser.parse(getClass().getResourceAsStream( - "/recipt.xml")); - - assertNotNull(document); - - } catch (IOException e) { - fail("Unexpected IOException " + e.getMessage()); - } catch (ParserConfigurationException e) { - fail("Unexpected ParserConfigurationException " + e.getMessage()); - } catch (SAXException e) { - fail("Unexpected SAXException " + e.getMessage()); - } - - dbf.setIgnoringElementContentWhitespace(false); - assertFalse(dbf.isIgnoringElementContentWhitespace()); - - try { - DocumentBuilder parser = dbf.newDocumentBuilder(); - - Document document = parser.parse(getClass().getResourceAsStream( - "/recipt.xml")); - - assertNotNull(document); - - } catch (IOException e) { - fail("Unexpected IOException " + e.getMessage()); - } catch (ParserConfigurationException e) { - fail("Unexpected ParserConfigurationException " + e.getMessage()); - } catch (SAXException e) { - fail("Unexpected SAXException " + e.getMessage()); - } - } - - /** - * javax.xml.parsers.DocumentBuilderFactory#setNamespaceAware(boolean). - */ - public void test_setNamespaceAwareZ() { - dbf.setNamespaceAware(true); - assertTrue(dbf.isNamespaceAware()); - - try { - DocumentBuilder parser = dbf.newDocumentBuilder(); - - Document document = parser.parse(getClass().getResourceAsStream( - "/recipt.xml")); - - assertNotNull(document); - - } catch (IOException e) { - fail("Unexpected IOException " + e.getMessage()); - } catch (ParserConfigurationException e) { - fail("Unexpected ParserConfigurationException " + e.getMessage()); - } catch (SAXException e) { - fail("Unexpected SAXException " + e.getMessage()); - } - - dbf.setNamespaceAware(false); - assertFalse(dbf.isNamespaceAware()); - - try { - DocumentBuilder parser = dbf.newDocumentBuilder(); - - Document document = parser.parse(getClass().getResourceAsStream( - "/recipt.xml")); - - assertNotNull(document); - - } catch (IOException e) { - fail("Unexpected IOException " + e.getMessage()); - } catch (ParserConfigurationException e) { - fail("Unexpected ParserConfigurationException " + e.getMessage()); - } catch (SAXException e) { - fail("Unexpected SAXException " + e.getMessage()); - } - } - - public void test_getSetAttribute() { - // Android SAX implementation doesn't support attributes, so - // we can only make sure the expected exception is thrown. - try { - dbf.setAttribute("foo", new Object()); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - // Expected - } - - try { - dbf.getAttribute("foo"); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - // Expected - } - } - - /** - * javax.xml.parsers.DocumentBuilderFactory#setSchema(javax.xml.validation.Schema). - */ - /* public void test_setSchemaLjavax_xml_validation_Schema() { - SchemaFactory sf = - SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - try { - Schema schema = sf.newSchema(); - dbf.setSchema(schema); - assertNotNull(dbf.getSchema()); - } catch (SAXException sax) { - fail("Unexpected exception " + sax.toString()); - } - } -*/ - /** - * javax.xml.parsers.DocumentBuilderFactory#setValidating(boolean). - */ -// public void test_setValidatingZ() { -// Exception parseException = null; -// DocumentBuilder parser = null; -// Document document = null; -// -// ValidationErrorHandler errorHandler = new ValidationErrorHandler(); -// -// dbf.setValidating(false); -// assertFalse(dbf.isValidating()); -// -// // case 1: Validation is not set. Correct xml-file -// try { -// -// parser = dbf.newDocumentBuilder(); -// parser.setErrorHandler(errorHandler); -// -// document = parser.parse(getClass().getResourceAsStream( -// "/recipt.xml")); -// -// parseException = errorHandler.getFirstException(); -// -// assertNotNull(document); -// -// document = parser.parse(getClass().getResourceAsStream( -// "/reciptWrong.xml")); -// -// parseException = errorHandler.getFirstException(); -// -// assertNotNull(document); -// -// } catch (Exception ex) { -// parseException = ex; -// } -// parser.setErrorHandler(null); -// -// if (parseException != null) { -// fail("Unexpected exception " + parseException.getMessage()); -// } -// -// // case 2: Validation is not set. Wrong xml-file -// try { -// -// parser = dbf.newDocumentBuilder(); -// parser.setErrorHandler(errorHandler); -// -// document = parser.parse(getClass().getResourceAsStream( -// "/reciptWrong.xml")); -// parseException = errorHandler.getFirstException(); -// -// assertNotNull(document); -// -// } catch (Exception ex) { -// parseException = ex; -// } -// parser.setErrorHandler(null); -// -// if (parseException != null) { -// fail("Unexpected exception " + parseException.getMessage()); -// } -// -// // case 3: Validation is set. Correct xml-file -// dbf.setValidating(true); -// assertTrue(dbf.isValidating()); -// -// try { -// -// parser = dbf.newDocumentBuilder(); -// parser.setErrorHandler(errorHandler); -// -// document = parser.parse(getClass().getResourceAsStream( -// "/recipt.xml")); -// parseException = errorHandler.getFirstException(); -// -// assertNotNull(document); -// -// } catch (Exception ex) { -// parseException = ex; -// } -// parser.setErrorHandler(null); -// -// if (parseException != null) { -// fail("Unexpected exception " + parseException.getMessage()); -// } -// -// // case 4: Validation is set. Wrong xml-file -// try { -// -// parser = dbf.newDocumentBuilder(); -// parser.setErrorHandler(errorHandler); -// -// document = parser.parse(getClass().getResourceAsStream( -// "/reciptWrong.xml")); -// parseException = errorHandler.getFirstException(); -// -// assertNotNull(document); -// -// } catch (Exception ex) { -// parseException = ex; -// } -// parser.setErrorHandler(null); -// -// if (parseException == null) { -// fail("Unexpected exception " + parseException.getMessage()); -// } else { -// assertTrue(parseException -// .getMessage() -// .contains( -// "The content of element type \"collection\" must match \"(description,recipe+)\"")); -// } -// -// } - - /** - * javax.xml.parsers.DocumentBuilderFactory#setXIncludeAware(). - */ -// public void test_setXIncludeAware() { -// dbf.setXIncludeAware(true); -// assertTrue(dbf.isXIncludeAware()); -// -// try { -// DocumentBuilder parser = dbf.newDocumentBuilder(); -// -// Document document = parser.parse(getClass().getResourceAsStream( -// "/recipt.xml")); -// -// assertNotNull(document); -// -// } catch (IOException e) { -// fail("Unexpected IOException " + e.getMessage()); -// } catch (ParserConfigurationException e) { -// fail("Unexpected ParserConfigurationException " + e.getMessage()); -// } catch (SAXException e) { -// fail("Unexpected SAXException " + e.getMessage()); -// } -// -// dbf.setXIncludeAware(false); -// assertFalse(dbf.isXIncludeAware()); -// -// try { -// DocumentBuilder parser = dbf.newDocumentBuilder(); -// -// Document document = parser.parse(getClass().getResourceAsStream( -// "/recipt.xml")); -// -// assertNotNull(document); -// -// } catch (IOException e) { -// fail("Unexpected IOException " + e.getMessage()); -// } catch (ParserConfigurationException e) { -// fail("Unexpected ParserConfigurationException " + e.getMessage()); -// } catch (SAXException e) { -// fail("Unexpected SAXException " + e.getMessage()); -// } -// } - - private void goThroughDocument(Node node, String indent) { - String value = node.getNodeValue(); - - if (value != null) { - value = value.replaceAll(" ", ""); - value = value.replaceAll("\n", ""); - } - - switch (node.getNodeType()) { - case Node.CDATA_SECTION_NODE: - cdataElements.add(value); - // System.out.println(indent + "CDATA_SECTION_NODE " + value); - break; - case Node.COMMENT_NODE: - commentElements.add(value); - // System.out.println(indent + "COMMENT_NODE " + value); - break; - case Node.DOCUMENT_FRAGMENT_NODE: - // System.out.println(indent + "DOCUMENT_FRAGMENT_NODE " + value); - break; - case Node.DOCUMENT_NODE: - // System.out.println(indent + "DOCUMENT_NODE " + value); - break; - case Node.DOCUMENT_TYPE_NODE: - // System.out.println(indent + "DOCUMENT_TYPE_NODE " + value); - break; - case Node.ELEMENT_NODE: - // System.out.println(indent + "ELEMENT_NODE " + value); - break; - case Node.ENTITY_NODE: - // System.out.println(indent + "ENTITY_NODE " + value); - break; - case Node.ENTITY_REFERENCE_NODE: - // System.out.println(indent + "ENTITY_REFERENCE_NODE " + value); - break; - case Node.NOTATION_NODE: - // System.out.println(indent + "NOTATION_NODE " + value); - break; - case Node.PROCESSING_INSTRUCTION_NODE: - // System.out.println(indent + "PROCESSING_INSTRUCTION_NODE " + - // value); - break; - case Node.TEXT_NODE: - textElements.add(value); - // System.out.println(indent + "TEXT_NODE " + value); - break; - default: - // System.out.println(indent + "Unknown node " + value); - break; - } - NodeList list = node.getChildNodes(); - for (int i = 0; i < list.getLength(); i++) - goThroughDocument(list.item(i), indent + " "); - } - - private class ValidationErrorHandler implements ErrorHandler { - private SAXException parseException; - - private int errorCount; - - private int warningCount; - - public ValidationErrorHandler() { - parseException = null; - errorCount = 0; - warningCount = 0; - } - - public void error(SAXParseException ex) { - errorCount++; - if (parseException == null) { - parseException = ex; - } - } - - public void warning(SAXParseException ex) { - warningCount++; - } - - public void fatalError(SAXParseException ex) { - if (parseException == null) { - parseException = ex; - } - } - - public SAXException getFirstException() { - return parseException; - } - } - - private class DocumentBuilderFactoryChild extends DocumentBuilderFactory { - public DocumentBuilderFactoryChild() { - super(); - } - - public Object getAttribute(String name) { - return null; - } - - public boolean getFeature(String name) { - return false; - } - - public DocumentBuilder newDocumentBuilder() { - return null; - } - - public void setAttribute(String name, Object value) { - } - - public void setFeature(String name, boolean value) { - } - - } -} diff --git a/luni/src/test/java/tests/api/javax/xml/parsers/DocumentBuilderTest.java b/luni/src/test/java/tests/api/javax/xml/parsers/DocumentBuilderTest.java deleted file mode 100644 index 66ce621..0000000 --- a/luni/src/test/java/tests/api/javax/xml/parsers/DocumentBuilderTest.java +++ /dev/null @@ -1,637 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.javax.xml.parsers; - -import junit.framework.TestCase; -import org.w3c.dom.DOMImplementation; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.EntityReference; -import org.w3c.dom.Text; -import org.xml.sax.EntityResolver; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; -import tests.api.org.xml.sax.support.MethodLogger; -import tests.api.org.xml.sax.support.MockHandler; -import tests.api.org.xml.sax.support.MockResolver; -import tests.support.resource.Support_Resources; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; - -public class DocumentBuilderTest extends TestCase { - - private class MockDocumentBuilder extends DocumentBuilder { - - public MockDocumentBuilder() { - super(); - } - - /* - * @see javax.xml.parsers.DocumentBuilder#getDOMImplementation() - */ - @Override - public DOMImplementation getDOMImplementation() { - // it is a fake - return null; - } - - /* - * @see javax.xml.parsers.DocumentBuilder#isNamespaceAware() - */ - @Override - public boolean isNamespaceAware() { - // it is a fake - return false; - } - - /* - * @see javax.xml.parsers.DocumentBuilder#isValidating() - */ - @Override - public boolean isValidating() { - // it is a fake - return false; - } - - /* - * @see javax.xml.parsers.DocumentBuilder#newDocument() - */ - @Override - public Document newDocument() { - // it is a fake - return null; - } - - /* - * @see javax.xml.parsers.DocumentBuilder#parse(org.xml.sax.InputSource) - */ - @Override - public Document parse(InputSource is) throws SAXException, IOException { - // it is a fake - return null; - } - - /* - * @see javax.xml.parsers.DocumentBuilder#setEntityResolver( - * org.xml.sax.EntityResolver) - */ - @Override - public void setEntityResolver(EntityResolver er) { - // it is a fake - } - - /* - * @see javax.xml.parsers.DocumentBuilder#setErrorHandler( - * org.xml.sax.ErrorHandler) - */ - @Override - public void setErrorHandler(ErrorHandler eh) { - // it is a fake - } - - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - } - - DocumentBuilderFactory dbf; - - DocumentBuilder db; - - protected void setUp() throws Exception { - - dbf = DocumentBuilderFactory.newInstance(); - - dbf.setIgnoringElementContentWhitespace(true); - - db = dbf.newDocumentBuilder(); - super.setUp(); - } - - protected void tearDown() throws Exception { - super.tearDown(); - } - - public void testDocumentBuilder() { - try { - new MockDocumentBuilder(); - } catch (Exception e) { - fail("unexpected exception " + e.toString()); - } - } - - /** - * javax.xml.parsers.DocumentBuilder#getSchema() - * TBD getSchema() is not supported - */ - /* public void test_getSchema() { - assertNull(db.getSchema()); - SchemaFactory sf = - SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - try { - Schema schema = sf.newSchema(); - dbf.setSchema(schema); - assertNotNull(dbf.newDocumentBuilder().getSchema()); - } catch (ParserConfigurationException pce) { - fail("Unexpected ParserConfigurationException " + pce.toString()); - } catch (SAXException sax) { - fail("Unexpected SAXException " + sax.toString()); - } - } -*/ - public void testNewDocument() { - Document d; - - try { - d = dbf.newDocumentBuilder().newDocument(); - } catch (Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertNotNull(d); - assertNull(d.getDoctype()); - assertNull(d.getDocumentElement()); - assertNull(d.getNamespaceURI()); - } - - public void testGetImplementation() { - DOMImplementation d; - - try { - d = dbf.newDocumentBuilder().getDOMImplementation(); - } catch (Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertNotNull(d); - } - - public void testIsNamespaceAware() { - try { - dbf.setNamespaceAware(true); - assertTrue(dbf.newDocumentBuilder().isNamespaceAware()); - dbf.setNamespaceAware(false); - assertFalse(dbf.newDocumentBuilder().isNamespaceAware()); - } catch (Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testIsValidating() { - try { - dbf.setValidating(false); - assertFalse(dbf.newDocumentBuilder().isValidating()); - } catch (Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testIsXIncludeAware() { - try { - dbf.setXIncludeAware(false); - assertFalse(dbf.newDocumentBuilder().isXIncludeAware()); - } catch (Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - /** - * Tests that the Base URI for the document is populated with the file URI. - */ - public void testGetBaseURI() throws IOException, SAXException { - File f = Support_Resources.resourceToTempFile("/simple.xml"); - Document d = db.parse(f); - assertTrue(d.getDocumentElement().getBaseURI().startsWith("file://")); - } - - /** - * javax.xml.parsers.DocumentBuilder#parse(java.io.File) - * Case 1: Try to parse correct xml document. - * Case 2: Try to call parse() with null argument. - * Case 3: Try to parse a non-existent file. - * Case 4: Try to parse incorrect xml file. - */ - public void test_parseLjava_io_File() throws IOException { - File f = Support_Resources.resourceToTempFile("/simple.xml"); - - // case 1: Trivial use. - try { - Document d = db.parse(f); - assertNotNull(d); - // TBD getXmlEncoding() IS NOT SUPPORTED - // assertEquals("ISO-8859-1", d.getXmlEncoding()); - assertEquals(2, d.getChildNodes().getLength()); - assertEquals("#comment", - d.getChildNodes().item(0).getNodeName()); - assertEquals("breakfast_menu", - d.getChildNodes().item(1).getNodeName()); - } catch (IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } catch (SAXException sax) { - fail("Unexpected SAXException " + sax.toString()); - } - - // case 2: Try to call parse with null argument - try { - db.parse((File)null); - fail("Expected IllegalArgumentException was not thrown"); - } catch (IllegalArgumentException iae) { - // expected - } catch (IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } catch (SAXException sax) { - fail("Unexpected SAXException " + sax.toString()); - } - - // case 3: Try to parse a non-existent file - try { - db.parse(new File("_")); - fail("Expected IOException was not thrown"); - } catch (IOException ioe) { - // expected - } catch (SAXException sax) { - fail("Unexpected SAXException " + sax.toString()); - } - - // case 4: Try to parse incorrect xml file - f = Support_Resources.resourceToTempFile("/wrong.xml"); - try { - db.parse(f); - fail("Expected SAXException was not thrown"); - } catch (IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } catch (SAXException sax) { - // expected - } - } - - /** - * javax.xml.parsers.DocumentBuilder#parse(java.io.InputStream) - * Case 1: Try to parse correct xml document. - * Case 2: Try to call parse() with null argument. - * Case 3: Try to parse a non-existent file. - * Case 4: Try to parse incorrect xml file. - */ - public void test_parseLjava_io_InputStream() { - InputStream is = getClass().getResourceAsStream("/simple.xml"); - // case 1: Trivial use. - try { - Document d = db.parse(is); - assertNotNull(d); - // TBD getXmlEncoding() IS NOT SUPPORTED - // assertEquals("ISO-8859-1", d.getXmlEncoding()); - assertEquals(2, d.getChildNodes().getLength()); - assertEquals("#comment", - d.getChildNodes().item(0).getNodeName()); - assertEquals("breakfast_menu", - d.getChildNodes().item(1).getNodeName()); - } catch (IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } catch (SAXException sax) { - fail("Unexpected SAXException " + sax.toString()); - } - - // case 2: Try to call parse with null argument - try { - db.parse((InputStream)null); - fail("Expected IllegalArgumentException was not thrown"); - } catch (IllegalArgumentException iae) { - // expected - } catch (IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } catch (SAXException sax) { - fail("Unexpected SAXException " + sax.toString()); - } - - // case 3: Try to parse a non-existent file - try { - db.parse(new FileInputStream("_")); - fail("Expected IOException was not thrown"); - } catch (IOException ioe) { - // expected - } catch (SAXException sax) { - fail("Unexpected SAXException " + sax.toString()); - } - - // case 4: Try to parse incorrect xml file - try { - is = getClass().getResourceAsStream("/wrong.xml"); - db.parse(is); - fail("Expected SAXException was not thrown"); - } catch (IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } catch (SAXException sax) { - // expected - } - } - - /** - * javax.xml.parsers.DocumentBuilder#parse(java.io.InputStream) - * Case 1: Try to parse correct xml document. - * Case 2: Try to call parse() with null argument. - * Case 3: Try to parse a non-existent file. - * Case 4: Try to parse incorrect xml file. - */ - public void testParseInputSource() { - InputStream stream = getClass().getResourceAsStream("/simple.xml"); - InputSource is = new InputSource(stream); - - // case 1: Trivial use. - try { - Document d = db.parse(is); - assertNotNull(d); - // TBD getXmlEncoding() IS NOT SUPPORTED - // assertEquals("ISO-8859-1", d.getXmlEncoding()); - assertEquals(2, d.getChildNodes().getLength()); - assertEquals("#comment", - d.getChildNodes().item(0).getNodeName()); - assertEquals("breakfast_menu", - d.getChildNodes().item(1).getNodeName()); - } catch (IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } catch (SAXException sax) { - fail("Unexpected SAXException " + sax.toString()); - } - - // case 2: Try to call parse with null argument - try { - db.parse((InputSource)null); - fail("Expected IllegalArgumentException was not thrown"); - } catch (IllegalArgumentException iae) { - // expected - } catch (IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } catch (SAXException sax) { - fail("Unexpected SAXException " + sax.toString()); - } - - // case 3: Try to parse a non-existent file - try { - db.parse(new InputSource(new FileInputStream("_"))); - fail("Expected IOException was not thrown"); - } catch (IOException ioe) { - // expected - } catch (SAXException sax) { - fail("Unexpected SAXException " + sax.toString()); - } - - // case 4: Try to parse incorrect xml file - try { - is = new InputSource(getClass().getResourceAsStream("/wrong.xml")); - db.parse(is); - fail("Expected SAXException was not thrown"); - } catch (IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } catch (SAXException sax) { - // expected - } - } - - /** - * javax.xml.parsers.DocumentBuilder#parse(java.io.InputStream, - * java.lang.String) - * Case 1: Try to parse correct xml document. - * Case 2: Try to call parse() with null argument. - * Case 3: Try to parse a non-existent file. - * Case 4: Try to parse incorrect xml file. - */ - public void test_parseLjava_io_InputStreamLjava_lang_String() { - InputStream is = getClass().getResourceAsStream("/systemid.xml"); - // case 1: Trivial use. - try { - Document d = db.parse(is, SAXParserTestSupport.XML_SYSTEM_ID); - assertNotNull(d); -// TBD getXmlEncoding() is not supported -// assertEquals("UTF-8", d.getXmlEncoding()); - assertEquals(4, d.getChildNodes().getLength()); - assertEquals("collection", - d.getChildNodes().item(0).getNodeName()); - assertEquals("#comment", - d.getChildNodes().item(1).getNodeName()); - assertEquals("collection", - d.getChildNodes().item(2).getNodeName()); - assertEquals("#comment", - d.getChildNodes().item(3).getNodeName()); - } catch (IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } catch (SAXException sax) { - fail("Unexpected SAXException " + sax.toString()); - } - - // case 2: Try to call parse with null argument - try { - db.parse((InputStream)null, SAXParserTestSupport.XML_SYSTEM_ID); - fail("Expected IllegalArgumentException was not thrown"); - } catch (IllegalArgumentException iae) { - // expected - } catch (IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } catch (SAXException sax) { - fail("Unexpected SAXException " + sax.toString()); - } - - // case 3: Try to parse a non-existent file -// Doesn't make sense this way... -// try { -// db.parse(is, "/"); -// fail("Expected IOException was not thrown"); -// } catch (IOException ioe) { -// // expected -// } catch (SAXException sax) { -// fail("Unexpected SAXException " + sax.toString()); -// } - - // case 4: Try to parse incorrect xml file - try { - is = getClass().getResourceAsStream("/wrong.xml"); - db.parse(is, SAXParserTestSupport.XML_SYSTEM_ID); - fail("Expected SAXException was not thrown"); - } catch (IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } catch (SAXException sax) { - // expected - } - } - - /** - * javax.xml.parsers.DocumentBuilder#parse(java.lang.String) - * Case 1: Try to parse correct xml document. - * Case 2: Try to call parse() with null argument. - * Case 3: Try to parse a non-existent uri. - * Case 4: Try to parse incorrect xml file. - */ - public void test_parseLjava_lang_String() throws Exception { - // case 1: Trivial use. - URL resource = getClass().getResource("/simple.xml"); - Document d = db.parse(resource.toString()); - assertNotNull(d); -// TBD getXmlEncoding() is not supported -// assertEquals("ISO-8859-1", d.getXmlEncoding()); - assertEquals(2, d.getChildNodes().getLength()); - assertEquals("#comment", - d.getChildNodes().item(0).getNodeName()); - assertEquals("breakfast_menu", - d.getChildNodes().item(1).getNodeName()); - - // case 2: Try to call parse with null argument - try { - db.parse((String)null); - fail("Expected IllegalArgumentException was not thrown"); - } catch (IllegalArgumentException iae) { - // expected - } - - // case 3: Try to parse a non-existent uri - try { - db.parse("_"); - fail("Expected IOException was not thrown"); - } catch (IOException ioe) { - // expected - } - - // case 4: Try to parse incorrect xml file - try { - resource = getClass().getResource("/wrong.xml"); - db.parse(resource.toString()); - fail("Expected SAXException was not thrown"); - } catch (SAXException sax) { - // expected - } - } - - public void testReset() { - // Make sure EntityResolver gets reset - InputStream source = new ByteArrayInputStream("<a>&foo;</a>".getBytes()); - InputStream entity = new ByteArrayInputStream("bar".getBytes()); - - MockResolver resolver = new MockResolver(); - resolver.addEntity("foo", "foo", new InputSource(entity)); - - Document d; - - try { - db = dbf.newDocumentBuilder(); - db.setEntityResolver(resolver); - db.reset(); - d = db.parse(source); - } catch (Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - - Element root = (Element)d.getElementsByTagName("a").item(0); - assertEquals("foo", ((EntityReference)root.getFirstChild()).getNodeName()); - - // Make sure ErrorHandler gets reset - source = new ByteArrayInputStream("</a>".getBytes()); - - MethodLogger logger = new MethodLogger(); - ErrorHandler handler = new MockHandler(logger); - - try { - db = dbf.newDocumentBuilder(); - db.setErrorHandler(handler); - db.reset(); - d = db.parse(source); - } catch (SAXParseException e) { - // Expected - } catch (Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(0, logger.size()); - } - - public void testSetErrorHandler() { - // Ordinary case - InputStream source = new ByteArrayInputStream("</a>".getBytes()); - - MethodLogger logger = new MethodLogger(); - ErrorHandler handler = new MockHandler(logger); - - try { - db = dbf.newDocumentBuilder(); - db.setErrorHandler(handler); - db.parse(source); - } catch (SAXParseException e) { - // Expected, ErrorHandler does not mask exception - } catch (Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals("error", logger.getMethod()); - assertTrue(logger.getArgs()[0] instanceof SAXParseException); - - // null case - source = new ByteArrayInputStream("</a>".getBytes()); - - try { - db = dbf.newDocumentBuilder(); - db.setErrorHandler(null); - db.parse(source); - } catch (SAXParseException e) { - // Expected - } catch (Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testSetEntityResolver() { - // Ordinary case - InputStream source = new ByteArrayInputStream("<a>&foo;</a>".getBytes()); - InputStream entity = new ByteArrayInputStream("bar".getBytes()); - - MockResolver resolver = new MockResolver(); - resolver.addEntity("foo", "foo", new InputSource(entity)); - - Document d; - - try { - db = dbf.newDocumentBuilder(); - db.setEntityResolver(resolver); - d = db.parse(source); - } catch (Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - - Element root = (Element)d.getElementsByTagName("a").item(0); - assertEquals("bar", ((Text)root.getFirstChild()).getData()); - - // null case - source = new ByteArrayInputStream("<a>&foo;</a>".getBytes()); - - try { - db = dbf.newDocumentBuilder(); - db.setEntityResolver(null); - d = db.parse(source); - } catch (Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - - root = (Element)d.getElementsByTagName("a").item(0); - assertEquals("foo", ((EntityReference)root.getFirstChild()).getNodeName()); - } - -} diff --git a/luni/src/test/java/tests/api/javax/xml/parsers/FactoryConfigurationErrorTest.java b/luni/src/test/java/tests/api/javax/xml/parsers/FactoryConfigurationErrorTest.java deleted file mode 100644 index cdef4e2..0000000 --- a/luni/src/test/java/tests/api/javax/xml/parsers/FactoryConfigurationErrorTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.javax.xml.parsers; - -import javax.xml.parsers.FactoryConfigurationError; - -import junit.framework.TestCase; - -public class FactoryConfigurationErrorTest extends TestCase { - - public void test_Constructor() { - FactoryConfigurationError fce = new FactoryConfigurationError(); - assertNull(fce.getMessage()); - assertNull(fce.getLocalizedMessage()); - assertNull(fce.getCause()); - } - - public void test_ConstructorLjava_lang_Exception() { - Exception e = new Exception(); - // case 1: Try to create FactoryConfigurationError - // which is based on Exception without parameters. - FactoryConfigurationError fce = new FactoryConfigurationError(e); - assertNotNull(fce.getMessage()); - assertNotNull(fce.getLocalizedMessage()); - assertEquals(e.getCause(), fce.getCause()); - - // case 2: Try to create FactoryConfigurationError - // which is based on Exception with String parameter. - e = new Exception("test message"); - fce = new FactoryConfigurationError(e); - assertEquals(e.toString(), fce.getMessage()); - assertEquals(e.toString(), fce.getLocalizedMessage()); - assertEquals(e.getCause(), fce.getCause()); - } - - public void test_ConstructorLjava_lang_ExceptionLjava_lang_String() { - Exception e = new Exception(); - // case 1: Try to create FactoryConfigurationError - // which is based on Exception without parameters. - FactoryConfigurationError fce = new FactoryConfigurationError(e, "msg"); - assertNotNull(fce.getMessage()); - assertNotNull(fce.getLocalizedMessage()); - assertEquals(e.getCause(), fce.getCause()); - - // case 2: Try to create FactoryConfigurationError - // which is based on Exception with String parameter. - e = new Exception("test message"); - fce = new FactoryConfigurationError(e, "msg"); - assertEquals("msg", fce.getMessage()); - assertEquals("msg", fce.getLocalizedMessage()); - assertEquals(e.getCause(), fce.getCause()); - } - - public void test_ConstructorLjava_lang_String() { - FactoryConfigurationError fce = new FactoryConfigurationError("Oops!"); - assertEquals("Oops!", fce.getMessage()); - assertEquals("Oops!", fce.getLocalizedMessage()); - assertNull(fce.getCause()); - } - - public void test_getException() { - FactoryConfigurationError fce = new FactoryConfigurationError(); - assertNull(fce.getException()); - fce = new FactoryConfigurationError("test"); - assertNull(fce.getException()); - Exception e = new Exception("msg"); - fce = new FactoryConfigurationError(e); - assertEquals(e, fce.getException()); - NullPointerException npe = new NullPointerException(); - fce = new FactoryConfigurationError(npe); - assertEquals(npe, fce.getException()); - } - - public void test_getMessage() { - assertNull(new FactoryConfigurationError().getMessage()); - assertEquals("msg1", - new FactoryConfigurationError("msg1").getMessage()); - assertEquals(new Exception("msg2").toString(), - new FactoryConfigurationError( - new Exception("msg2")).getMessage()); - assertEquals(new NullPointerException().toString(), - new FactoryConfigurationError( - new NullPointerException()).getMessage()); - } - -} diff --git a/luni/src/test/java/tests/api/javax/xml/parsers/ParserConfigurationExceptionTest.java b/luni/src/test/java/tests/api/javax/xml/parsers/ParserConfigurationExceptionTest.java deleted file mode 100644 index d1feb9f..0000000 --- a/luni/src/test/java/tests/api/javax/xml/parsers/ParserConfigurationExceptionTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.javax.xml.parsers; - -import javax.xml.parsers.ParserConfigurationException; - -import junit.framework.TestCase; - -public class ParserConfigurationExceptionTest extends TestCase{ - - public void test_Constructor() { - ParserConfigurationException pce = new ParserConfigurationException(); - assertNull(pce.getMessage()); - assertNull(pce.getLocalizedMessage()); - assertNull(pce.getCause()); - } - - public void test_ConstructorLjava_lang_String() { - ParserConfigurationException pce = - new ParserConfigurationException("Oops!"); - assertEquals("Oops!", pce.getMessage()); - assertEquals("Oops!", pce.getLocalizedMessage()); - assertNull(pce.getCause()); - } - -} diff --git a/luni/src/test/java/tests/api/javax/xml/parsers/SAXParserFactoryTest.java b/luni/src/test/java/tests/api/javax/xml/parsers/SAXParserFactoryTest.java deleted file mode 100644 index 614b9d8..0000000 --- a/luni/src/test/java/tests/api/javax/xml/parsers/SAXParserFactoryTest.java +++ /dev/null @@ -1,415 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.javax.xml.parsers; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Properties; -import java.util.Vector; - -import javax.xml.parsers.FactoryConfigurationError; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; - -import junit.framework.TestCase; - -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; -import org.xml.sax.SAXNotRecognizedException; -import org.xml.sax.SAXNotSupportedException; -import org.xml.sax.helpers.DefaultHandler; - -import dalvik.annotation.AndroidOnly; -import dalvik.annotation.KnownFailure; - -public class SAXParserFactoryTest extends TestCase { - - SAXParserFactory spf; - - InputStream is1; - - static HashMap<String, String> ns; - - static Vector<String> el; - - static HashMap<String, String> attr; - - public void setUp() throws Exception { - spf = SAXParserFactory.newInstance(); - - is1 = getClass().getResourceAsStream("/simple.xml"); - - ns = new HashMap<String, String>(); - attr = new HashMap<String, String>(); - el = new Vector<String>(); - } - - public void tearDown() throws Exception { - is1.close(); - super.tearDown(); - } - - @AndroidOnly("Android SAX implementation is non-validating") - public void test_Constructor() { - MySAXParserFactory mpf = new MySAXParserFactory(); - assertTrue(mpf instanceof SAXParserFactory); - assertFalse(mpf.isValidating()); - } - - /** - * javax.xml.parsers.SAXParserFactory#getSchema(). - * TBD getSchema() IS NOT SUPPORTED - */ - /* public void test_getSchema() { - assertNull(spf.getSchema()); - SchemaFactory sf = - SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - try { - Schema schema = sf.newSchema(); - spf.setSchema(schema); - assertNotNull(spf.getSchema()); - } catch (SAXException sax) { - fail("Unexpected exception " + sax.toString()); - } - } - */ - - public void test_setIsNamespaceAware() { - spf.setNamespaceAware(true); - assertTrue(spf.isNamespaceAware()); - spf.setNamespaceAware(false); - assertFalse(spf.isNamespaceAware()); - spf.setNamespaceAware(true); - assertTrue(spf.isNamespaceAware()); - } - - public void test_setIsValidating() { - spf.setValidating(true); - assertTrue(spf.isValidating()); - spf.setValidating(false); - assertFalse(spf.isValidating()); - spf.setValidating(true); - assertTrue(spf.isValidating()); - } - - public void test_setIsXIncludeAware() { - spf.setXIncludeAware(true); - assertTrue(spf.isXIncludeAware()); - spf.setXIncludeAware(false); - assertFalse(spf.isXIncludeAware()); - } - - @KnownFailure("Dalvik doesn't honor system properties when choosing a SAX implementation") - public void test_newInstance() { - try { - SAXParserFactory dtf = SAXParserFactory.newInstance(); - assertNotNull("New Instance of DatatypeFactory is null", dtf); - - System.setProperty("javax.xml.parsers.SAXParserFactory", - "org.apache.harmony.xml.parsers.SAXParserFactoryImpl"); - - SAXParserFactory spf1 = SAXParserFactory.newInstance(); - assertTrue(spf1 instanceof org.apache.harmony.xml.parsers.SAXParserFactoryImpl); - - String key = "javax.xml.parsers.SAXParserFactory = org.apache.harmony.xml.parsers.SAXParserFactoryImpl"; - - ByteArrayInputStream bis = new ByteArrayInputStream(key.getBytes()); - Properties prop = System.getProperties(); - prop.load(bis); - SAXParserFactory spf2 = SAXParserFactory.newInstance(); - assertTrue(spf2 instanceof org.apache.harmony.xml.parsers.SAXParserFactoryImpl); - - System.setProperty("javax.xml.parsers.SAXParserFactory", ""); - try { - SAXParserFactory.newInstance(); - fail("Expected FactoryConfigurationError was not thrown"); - } catch (FactoryConfigurationError e) { - // expected - } - } catch (IOException ioe) { - fail("Unexpected exception " + ioe.toString()); - } - } - - public void test_newSAXParser() { - // Ordinary case - try { - SAXParser sp = spf.newSAXParser(); - assertTrue(sp instanceof SAXParser); - sp.parse(is1, new MyHandler()); - } catch(Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - - // Exception case - spf.setValidating(true); - try { - SAXParser sp = spf.newSAXParser(); - } catch(ParserConfigurationException e) { - // Expected, since Android doesn't have a validating parser. - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void test_setFeatureLjava_lang_StringZ() { - // We can't verify ParserConfigurationException and - // SAXNotSupportedException since these are never - // thrown by Android. - - String[] features = { - "http://xml.org/sax/features/namespaces", - "http://xml.org/sax/features/validation" }; - for (int i = 0; i < features.length; i++) { - try { - spf.setFeature(features[i], true); - assertTrue(spf.getFeature(features[i])); - spf.setFeature(features[i], false); - assertFalse(spf.getFeature(features[i])); - } catch (ParserConfigurationException pce) { - fail("ParserConfigurationException is thrown"); - } catch (SAXNotRecognizedException snre) { - fail("SAXNotRecognizedException is thrown"); - } catch (SAXNotSupportedException snse) { - fail("SAXNotSupportedException is thrown"); - } - } - - try { - spf.setFeature("", true); - fail("SAXNotRecognizedException is not thrown"); - } catch (ParserConfigurationException pce) { - fail("ParserConfigurationException is thrown"); - } catch (SAXNotRecognizedException snre) { - //expected - } catch (SAXNotSupportedException snse) { - fail("SAXNotSupportedException is thrown"); - } catch (NullPointerException npe) { - fail("NullPointerException is thrown"); - } - - try { - spf.setFeature("http://xml.org/sax/features/unknown-feature", true); - } catch (ParserConfigurationException pce) { - fail("ParserConfigurationException is thrown"); - } catch (SAXNotRecognizedException snre) { - fail("SAXNotRecognizedException is thrown"); - } catch (SAXNotSupportedException snse) { - // Acceptable, although this doesn't happen an Android. - } catch (NullPointerException npe) { - fail("NullPointerException is thrown"); - } - - try { - spf.setFeature(null, true); - fail("NullPointerException is not thrown"); - } catch (ParserConfigurationException pce) { - fail("ParserConfigurationException is thrown"); - } catch (SAXNotRecognizedException snre) { - fail("SAXNotRecognizedException is thrown"); - } catch (SAXNotSupportedException snse) { - fail("SAXNotSupportedException is thrown"); - } catch (NullPointerException npe) { - // expected - } - } - - public void test_setNamespaceAwareZ() throws Exception { - MyHandler mh = new MyHandler(); - - spf.setNamespaceAware(true); - InputStream is = getClass().getResourceAsStream("/simple_ns.xml"); - spf.newSAXParser().parse(is, mh); - is.close(); - - spf.setNamespaceAware(false); - is = getClass().getResourceAsStream("/simple_ns.xml"); - spf.newSAXParser().parse(is, mh); - is.close(); - } - - /* public void test_setSchemaLjavax_xml_validation_Schema() { - SchemaFactory sf = - SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - try { - Schema schema = sf.newSchema(); - spf.setSchema(schema); - assertNotNull(spf.getSchema()); - } catch (SAXException sax) { - fail("Unexpected exception " + sax.toString()); - } - } - */ - -// public void test_setValidatingZ() { -// MyHandler mh = new MyHandler(); -// InputStream is2 = getClass().getResourceAsStream("/recipe.xml"); -// try { -// spf.setValidating(true); -// assertTrue(spf.isValidating()); -// spf.newSAXParser().parse(is2, mh); -// } catch (org.xml.sax.SAXException se) { -// fail("SAXException was thrown during parsing"); -// } catch (javax.xml.parsers.ParserConfigurationException pce) { -// fail("ParserConfigurationException was thrown during parsing"); -// } catch (IOException ioe) { -// fail("IOException was thrown during parsing"); -// } finally { -// try { -// is2.close(); -// } catch(Exception ioee) {} -// } -// InputStream is3 = getClass().getResourceAsStream("/recipe1.xml"); -// try { -// assertTrue(spf.isValidating()); -// spf.newSAXParser().parse(is3, mh); -// } catch (org.xml.sax.SAXException se) { -// fail("SAXException was thrown during parsing"); -// } catch (javax.xml.parsers.ParserConfigurationException pce) { -// fail("ParserConfigurationException was thrown during parsing"); -// } catch (IOException ioe) { -// fail("IOEXception was thrown during parsing: " + ioe.getMessage()); -// } finally { -// try { -// is3.close(); -// } catch(Exception ioee) {} -// } -// is2 = getClass().getResourceAsStream("/recipe.xml"); -// try { -// spf.setValidating(false); -// assertFalse(spf.isValidating()); -// spf.newSAXParser().parse(is2, mh); -// } catch (org.xml.sax.SAXException se) { -// fail("SAXException was thrown during parsing"); -// } catch (javax.xml.parsers.ParserConfigurationException pce) { -// fail("ParserConfigurationException was thrown during parsing"); -// } catch (IOException ioe) { -// fail("IOException was thrown during parsing"); -// } finally { -// try { -// is2.close(); -// } catch(Exception ioee) {} -// } -// is3 = getClass().getResourceAsStream("/recipe1.xml"); -// try { -// assertFalse(spf.isValidating()); -// spf.newSAXParser().parse(is3, mh); -// } catch (org.xml.sax.SAXException se) { -// fail("SAXException was thrown during parsing"); -// } catch (javax.xml.parsers.ParserConfigurationException pce) { -// fail("ParserConfigurationException was thrown during parsing"); -// } catch (IOException ioe) { -// fail("IOEXception was thrown during parsing: " + ioe.getMessage()); -// } finally { -// try { -// is3.close(); -// } catch(Exception ioee) {} -// } -// } - -// public void test_setXIncludeAwareZ() { -// spf.setXIncludeAware(true); -// MyHandler mh = new MyHandler(); -// InputStream is = getClass().getResourceAsStream("/simple_ns.xml"); -// try { -// spf.newSAXParser().parse(is, mh); -// } catch(javax.xml.parsers.ParserConfigurationException pce) { -// fail("ParserConfigurationException was thrown during parsing"); -// } catch(org.xml.sax.SAXException se) { -// fail("SAXException was thrown during parsing"); -// } catch(IOException ioe) { -// fail("IOException was thrown during parsing"); -// } finally { -// try { -// is.close(); -// } catch(Exception ioee) {} -// } -// spf.setXIncludeAware(false); -// is = getClass().getResourceAsStream("/simple_ns.xml"); -// try { -// is = getClass().getResourceAsStream("/simple_ns.xml"); -// spf.newSAXParser().parse(is, mh); -// } catch(javax.xml.parsers.ParserConfigurationException pce) { -// fail("ParserConfigurationException was thrown during parsing"); -// } catch(org.xml.sax.SAXException se) { -// fail("SAXException was thrown during parsing"); -// } catch(IOException ioe) { -// fail("IOException was thrown during parsing"); -// } finally { -// try { -// is.close(); -// } catch(Exception ioee) {} -// } -// is = getClass().getResourceAsStream("/simple_ns.xml"); -// try { -// spf.setXIncludeAware(true); -// spf.newSAXParser().parse(is, mh); -// } catch(javax.xml.parsers.ParserConfigurationException pce) { -// fail("ParserConfigurationException was thrown during parsing"); -// } catch(org.xml.sax.SAXException se) { -// fail("SAXException was thrown during parsing"); -// } catch(IOException ioe) { -// fail("IOException was thrown during parsing"); -// } finally { -// try { -// is.close(); -// } catch(Exception ioee) {} -// } -// } - - static class MyHandler extends DefaultHandler { - - public void startElement(String uri, String localName, String qName, - Attributes atts) { - - el.add(qName); - if (!uri.equals("")) - ns.put(qName, uri); - for (int i = 0; i < atts.getLength(); i++) { - attr.put(atts.getQName(i), atts.getValue(i)); - } - - } - } - - class MySAXParserFactory extends SAXParserFactory { - - public MySAXParserFactory() { - super(); - } - - public SAXParser newSAXParser() { - return null; - } - - public void setFeature(String name, boolean value) throws - ParserConfigurationException, SAXNotRecognizedException, - SAXNotSupportedException { - - } - - public boolean getFeature(String name) throws - ParserConfigurationException, SAXNotRecognizedException, - SAXNotSupportedException { - return true; - } - - } - -} diff --git a/luni/src/test/java/tests/api/javax/xml/parsers/SAXParserTest.java b/luni/src/test/java/tests/api/javax/xml/parsers/SAXParserTest.java deleted file mode 100644 index 3586162..0000000 --- a/luni/src/test/java/tests/api/javax/xml/parsers/SAXParserTest.java +++ /dev/null @@ -1,922 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.javax.xml.parsers; - -import dalvik.annotation.KnownFailure; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.HashMap; -import java.util.Vector; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; -import junit.framework.TestCase; -import org.xml.sax.HandlerBase; -import org.xml.sax.InputSource; -import org.xml.sax.Parser; -import org.xml.sax.SAXException; -import org.xml.sax.SAXNotRecognizedException; -import org.xml.sax.SAXNotSupportedException; -import org.xml.sax.XMLReader; -import org.xml.sax.ext.LexicalHandler; -import org.xml.sax.helpers.DefaultHandler; -import tests.api.javax.xml.parsers.SAXParserTestSupport.MyDefaultHandler; -import tests.api.javax.xml.parsers.SAXParserTestSupport.MyHandler; -import tests.api.org.xml.sax.support.BrokenInputStream; -import tests.api.org.xml.sax.support.MethodLogger; -import tests.api.org.xml.sax.support.MockHandler; -import tests.support.resource.Support_Resources; - -@SuppressWarnings("deprecation") -public class SAXParserTest extends TestCase { - - private class MockSAXParser extends SAXParser { - public MockSAXParser() { - super(); - } - - /* - * @see javax.xml.parsers.SAXParser#getParser() - */ - @Override - public Parser getParser() throws SAXException { - // it is a fake - return null; - } - - /* - * @see javax.xml.parsers.SAXParser#getProperty(java.lang.String) - */ - @Override - public Object getProperty(String name) throws SAXNotRecognizedException, - SAXNotSupportedException { - // it is a fake - return null; - } - - /* - * @see javax.xml.parsers.SAXParser#getXMLReader() - */ - @Override - public XMLReader getXMLReader() throws SAXException { - // it is a fake - return null; - } - - /* - * @see javax.xml.parsers.SAXParser#isNamespaceAware() - */ - @Override - public boolean isNamespaceAware() { - // it is a fake - return false; - } - - /* - * @see javax.xml.parsers.SAXParser#isValidating() - */ - @Override - public boolean isValidating() { - // it is a fake - return false; - } - - /* - * @see javax.xml.parsers.SAXParser#setProperty(java.lang.String, - * java.lang.Object) - */ - @Override - public void setProperty(String name, Object value) throws - SAXNotRecognizedException, SAXNotSupportedException { - // it is a fake - } - } - - private static final String LEXICAL_HANDLER_PROPERTY - = "http://xml.org/sax/properties/lexical-handler"; - - SAXParserFactory spf; - - SAXParser parser; - - static HashMap<String, String> ns; - - static Vector<String> el; - - static HashMap<String, String> attr; - - SAXParserTestSupport sp = new SAXParserTestSupport(); - - File [] list_wf; - File [] list_nwf; - File [] list_out_dh; - File [] list_out_hb; - - boolean validating = false; - - private InputStream getResource(String name) { - return this.getClass().getResourceAsStream(name); - } - - public void initFiles() throws Exception { - // we differntiate between a validating and a non validating parser - try { - SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); - validating = parser.isValidating(); - } catch (Exception e) { - fail("could not obtain a SAXParser"); - } - - String tmpPath = System.getProperty("java.io.tmpdir"); - - // nwf = not well formed, wf = well formed - list_wf = new File[] {new File(tmpPath + "/" + - SAXParserTestSupport.XML_WF + "staff.xml")}; - list_nwf = new File[] {new File(tmpPath + "/" + - SAXParserTestSupport.XML_NWF + "staff.xml")}; - list_out_dh = new File[] {new File(tmpPath + "/" + - SAXParserTestSupport.XML_WF_OUT_DH + "staff.out")}; - list_out_hb = new File[] {new File(tmpPath + "/" + - SAXParserTestSupport.XML_WF_OUT_HB + "staff.out")}; - - list_wf[0].deleteOnExit(); - list_nwf[0].deleteOnExit(); - list_out_hb[0].deleteOnExit(); - list_out_dh[0].deleteOnExit(); - - - Support_Resources.copyLocalFileto(list_wf[0], - getResource(SAXParserTestSupport.XML_WF + "staff.xml")); - Support_Resources.copyLocalFileto(new File( - tmpPath + "/" + SAXParserTestSupport.XML_WF + "staff.dtd"), - getResource(SAXParserTestSupport.XML_WF + "staff.dtd")); - - Support_Resources.copyLocalFileto(list_nwf[0], - getResource(SAXParserTestSupport.XML_NWF + "staff.xml")); - Support_Resources.copyLocalFileto(new File( - tmpPath + "/" + SAXParserTestSupport.XML_NWF + "staff.dtd"), - getResource(SAXParserTestSupport.XML_NWF + "staff.dtd")); - - Support_Resources.copyLocalFileto(list_out_dh[0], - getResource(SAXParserTestSupport.XML_WF_OUT_DH + "staff.out")); - Support_Resources.copyLocalFileto(list_out_hb[0], - getResource(SAXParserTestSupport.XML_WF_OUT_HB + "staff.out")); - } - - @Override - protected void setUp() throws Exception { - spf = SAXParserFactory.newInstance(); - parser = spf.newSAXParser(); - assertNotNull(parser); - - ns = new HashMap<String, String>(); - attr = new HashMap<String, String>(); - el = new Vector<String>(); - initFiles(); - } - - @Override - protected void tearDown() throws Exception { - } - -// public static void main(String[] args) throws Exception { -// SAXParserTest st = new SAXParserTest(); -// st.setUp(); -// st.generateDataFromReferenceImpl(); -// -// } -// -// private void generateDataFromReferenceImpl() { -// try { -// for(int i = 0; i < list_wf.length; i++) { -// MyDefaultHandler dh = new MyDefaultHandler(); -// InputStream is = new FileInputStream(list_wf[i]); -// parser.parse(is, dh, ParsingSupport.XML_SYSTEM_ID); -// HashMap refHm = dh.createData(); -// -// StringBuilder sb = new StringBuilder(); -// for (int j = 0; j < ParsingSupport.KEYS.length; j++) { -// String key = ParsingSupport.KEYS[j]; -// sb.append(refHm.get(key)).append( -// ParsingSupport.SEPARATOR_DATA); -// } -// FileWriter fw = new FileWriter("/tmp/build_dh"+i+".out"); -// fw.append(sb.toString()); -// fw.close(); -// } -// -// for(int i = 0; i < list_nwf.length; i++) { -// MyHandler hb = new MyHandler(); -// InputStream is = new FileInputStream(list_wf[i]); -// parser.parse(is, hb, ParsingSupport.XML_SYSTEM_ID); -// HashMap refHm = hb.createData(); -// -// StringBuilder sb = new StringBuilder(); -// for (int j = 0; j < ParsingSupport.KEYS.length; j++) { -// String key = ParsingSupport.KEYS[j]; -// sb.append(refHm.get(key)).append( -// ParsingSupport.SEPARATOR_DATA); -// } -// FileWriter fw = new FileWriter("/tmp/build_hb"+i+".out"); -// fw.append(sb.toString()); -// fw.close(); -// } -// -// -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } - - public void testSAXParser() { - try { - new MockSAXParser(); - } catch (Exception e) { - fail("unexpected exception " + e.toString()); - } - } - - /** - * javax.xml.parser.SAXParser#getSchema(). - * TODO getSchema() IS NOT SUPPORTED - */ - /* public void test_getSchema() { - assertNull(parser.getSchema()); - SchemaFactory sf = - SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - try { - Schema schema = sf.newSchema(); - spf.setSchema(schema); - assertNotNull(spf.newSAXParser().getSchema()); - } catch (ParserConfigurationException pce) { - fail("Unexpected ParserConfigurationException " + pce.toString()); - } catch (SAXException sax) { - fail("Unexpected SAXException " + sax.toString()); - } - } - */ - - public void testIsNamespaceAware() { - try { - spf.setNamespaceAware(true); - assertTrue(spf.newSAXParser().isNamespaceAware()); - spf.setNamespaceAware(false); - assertFalse(spf.newSAXParser().isNamespaceAware()); - } catch (Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testIsValidating() { - try { - spf.setValidating(false); - assertFalse(spf.newSAXParser().isValidating()); - } catch (Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testIsXIncludeAware() { - try { - spf.setXIncludeAware(false); - assertFalse(spf.newSAXParser().isXIncludeAware()); - } catch (Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - /** - * @test javax.xml.parsers.SAXParser#parse(java.io.File, - * org.xml.sax.helpers.DefaultHandler) - */ - public void test_parseLjava_io_FileLorg_xml_sax_helpers_DefaultHandler() - throws Exception { - - for(int i = 0; i < list_wf.length; i++) { - HashMap<String, String> hm = - new SAXParserTestSupport().readFile(list_out_dh[i].getPath()); - MyDefaultHandler dh = new MyDefaultHandler(); - parser.parse(list_wf[i], dh); - assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData())); - } - - for(int i = 0; i < list_nwf.length; i++) { - try { - MyDefaultHandler dh = new MyDefaultHandler(); - parser.parse(list_nwf[i], dh); - fail("SAXException is not thrown"); - } catch(org.xml.sax.SAXException se) { - //expected - } - } - - try { - MyDefaultHandler dh = new MyDefaultHandler(); - parser.parse((File) null, dh); - fail("java.lang.IllegalArgumentException is not thrown"); - } catch(java.lang.IllegalArgumentException iae) { - //expected - } - - try { - parser.parse(list_wf[0], (DefaultHandler) null); - } catch(java.lang.IllegalArgumentException iae) { - fail("java.lang.IllegalArgumentException is thrown"); - } - } - - public void testParseFileHandlerBase() { - for(int i = 0; i < list_wf.length; i++) { - try { - HashMap<String, String> hm = sp.readFile( - list_out_hb[i].getPath()); - MyHandler dh = new MyHandler(); - parser.parse(list_wf[i], dh); - assertTrue(SAXParserTestSupport.equalsMaps(hm, - dh.createData())); - } catch (IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } catch (SAXException sax) { - fail("Unexpected SAXException " + sax.toString()); - } - } - - for(int i = 0; i < list_nwf.length; i++) { - try { - MyHandler dh = new MyHandler(); - parser.parse(list_nwf[i], dh); - fail("SAXException is not thrown"); - } catch(org.xml.sax.SAXException se) { - //expected - } catch (FileNotFoundException fne) { - fail("Unexpected FileNotFoundException " + fne.toString()); - } catch (IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } - } - - try { - MyHandler dh = new MyHandler(); - parser.parse((File) null, dh); - fail("java.lang.IllegalArgumentException is not thrown"); - } catch(java.lang.IllegalArgumentException iae) { - //expected - } catch (IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } catch(SAXException sax) { - fail("Unexpected SAXException " + sax.toString()); - } - - try { - parser.parse(list_wf[0], (HandlerBase) null); - } catch(java.lang.IllegalArgumentException iae) { - fail("java.lang.IllegalArgumentException is thrown"); - } catch (FileNotFoundException fne) { - fail("Unexpected FileNotFoundException " + fne.toString()); - } catch(IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } catch(SAXException sax) { - fail("Unexpected SAXException " + sax.toString()); - } - } - - /** - * @test javax.xml.parsers.SAXParser#parse(org.xml.sax.InputSource, - * org.xml.sax.helpers.DefaultHandler) - */ - public void test_parseLorg_xml_sax_InputSourceLorg_xml_sax_helpers_DefaultHandler() - throws Exception { - for(int i = 0; i < list_wf.length; i++) { - HashMap<String, String> hm = new SAXParserTestSupport().readFile( - list_out_dh[i].getPath()); - MyDefaultHandler dh = new MyDefaultHandler(); - InputSource is = new InputSource(new FileInputStream(list_wf[i])); - parser.parse(is, dh); - assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData())); - } - - for (File file : list_nwf) { - try { - MyDefaultHandler dh = new MyDefaultHandler(); - InputSource is = new InputSource(new FileInputStream(file)); - parser.parse(is, dh); - fail("SAXException is not thrown"); - } catch (SAXException expected) { - } - } - - try { - MyDefaultHandler dh = new MyDefaultHandler(); - parser.parse((InputSource) null, dh); - fail("java.lang.IllegalArgumentException is not thrown"); - } catch (IllegalArgumentException expected) { - } - - InputSource is = new InputSource(new FileInputStream(list_wf[0])); - parser.parse(is, (DefaultHandler) null); - - InputStream in = null; - try { - in = new BrokenInputStream(new FileInputStream(list_wf[0]), 10); - is = new InputSource(in); - parser.parse(is, (DefaultHandler) null); - fail("IOException expected"); - } catch(IOException expected) { - } finally { - in.close(); - } - } - - public void testParseInputSourceHandlerBase() throws Exception { - for(int i = 0; i < list_wf.length; i++) { - HashMap<String, String> hm = sp.readFile(list_out_hb[i].getPath()); - MyHandler dh = new MyHandler(); - InputSource is = new InputSource(new FileInputStream(list_wf[i])); - parser.parse(is, dh); - assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData())); - } - - for (File file : list_nwf) { - try { - MyHandler dh = new MyHandler(); - InputSource is = new InputSource(new FileInputStream(file)); - parser.parse(is, dh); - fail("SAXException is not thrown"); - } catch (SAXException expected) { - } - } - - try { - MyHandler dh = new MyHandler(); - parser.parse((InputSource) null, dh); - fail("java.lang.IllegalArgumentException is not thrown"); - } catch(IllegalArgumentException expected) { - } - - InputSource is = new InputSource(new FileInputStream(list_wf[0])); - parser.parse(is, (HandlerBase) null); - - // Reader case - is = new InputSource(new InputStreamReader(new FileInputStream(list_wf[0]))); - parser.parse(is, (HandlerBase) null); - - // SystemID case - is = new InputSource(list_wf[0].toURI().toString()); - parser.parse(is, (HandlerBase) null); - - // Inject IOException - InputStream in = null; - try { - in = new BrokenInputStream(new FileInputStream(list_wf[0]), 10); - parser.parse(in, (HandlerBase) null, SAXParserTestSupport.XML_SYSTEM_ID); - fail("IOException expected"); - } catch(IOException expected) { - } finally { - in.close(); - } - } - - /** - * @test javax.xml.parsers.SAXParser#parse(java.io.InputStream, - * org.xml.sax.helpers.DefaultHandler) - */ - public void test_parseLjava_io_InputStreamLorg_xml_sax_helpers_DefaultHandler() - throws Exception { - - for(int i = 0; i < list_wf.length; i++) { - - HashMap<String, String> hm = new SAXParserTestSupport().readFile( - list_out_dh[i].getPath()); - MyDefaultHandler dh = new MyDefaultHandler(); - InputStream is = new FileInputStream(list_wf[i]); - parser.parse(is, dh); - assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData())); - } - - for(int i = 0; i < list_nwf.length; i++) { - try { - MyDefaultHandler dh = new MyDefaultHandler(); - InputStream is = new FileInputStream(list_nwf[i]); - parser.parse(is, dh); - fail("SAXException is not thrown"); - } catch(org.xml.sax.SAXException se) { - //expected - } - } - - try { - MyDefaultHandler dh = new MyDefaultHandler(); - parser.parse((InputStream) null, dh); - fail("java.lang.IllegalArgumentException is not thrown"); - } catch(java.lang.IllegalArgumentException iae) { - //expected - } - - try { - InputStream is = new FileInputStream(list_wf[0]); - parser.parse(is, (DefaultHandler) null); - } catch(java.lang.IllegalArgumentException iae) { - fail("java.lang.IllegalArgumentException is thrown"); - } - } - - /** - * @test javax.xml.parsers.SAXParser#parse(java.io.InputStream, - * org.xml.sax.helpers.DefaultHandler, java.lang.String) - */ - @KnownFailure("We supply optional qnames, but this test doesn't expect them") - public void test_parseLjava_io_InputStreamLorg_xml_sax_helpers_DefaultHandlerLjava_lang_String() { - for(int i = 0; i < list_wf.length; i++) { - try { - HashMap<String, String> hm = sp.readFile( - list_out_hb[i].getPath()); - MyDefaultHandler dh = new MyDefaultHandler(); - InputStream is = new FileInputStream(list_wf[i]); - parser.parse(is, dh, SAXParserTestSupport.XML_SYSTEM_ID); - assertEquals(hm, dh.createData()); - } catch (IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } catch (SAXException sax) { - fail("Unexpected SAXException " + sax.toString()); - } - } - - for(int i = 0; i < list_nwf.length; i++) { - try { - MyDefaultHandler dh = new MyDefaultHandler(); - InputStream is = new FileInputStream(list_nwf[i]); - parser.parse(is, dh, SAXParserTestSupport.XML_SYSTEM_ID); - fail("SAXException is not thrown"); - } catch(org.xml.sax.SAXException se) { - //expected - } catch (FileNotFoundException fne) { - fail("Unexpected FileNotFoundException " + fne.toString()); - } catch (IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } - } - - try { - MyDefaultHandler dh = new MyDefaultHandler(); - parser.parse((InputStream) null, dh, - SAXParserTestSupport.XML_SYSTEM_ID); - fail("java.lang.IllegalArgumentException is not thrown"); - } catch(java.lang.IllegalArgumentException iae) { - //expected - } catch (IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } catch(SAXException sax) { - fail("Unexpected SAXException " + sax.toString()); - } - - try { - InputStream is = new FileInputStream(list_wf[0]); - parser.parse(is, (DefaultHandler) null, - SAXParserTestSupport.XML_SYSTEM_ID); - } catch(java.lang.IllegalArgumentException iae) { - fail("java.lang.IllegalArgumentException is thrown"); - } catch (FileNotFoundException fne) { - fail("Unexpected FileNotFoundException " + fne.toString()); - } catch(IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } catch(SAXException sax) { - fail("Unexpected SAXException " + sax.toString()); - } -// -// for(int i = 0; i < list_wf.length; i++) { -// -// HashMap<String, String> hm = new SAXParserTestSupport().readFile( -// list_out_dh[i].getPath()); -// MyDefaultHandler dh = new MyDefaultHandler(); -// InputStream is = new FileInputStream(list_wf[i]); -// parser.parse(is, dh, SAXParserTestSupport.XML_SYSTEM_ID); -// assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData())); -// } -// -// for(int i = 0; i < list_nwf.length; i++) { -// try { -// MyDefaultHandler dh = new MyDefaultHandler(); -// InputStream is = new FileInputStream(list_nwf[i]); -// parser.parse(is, dh, SAXParserTestSupport.XML_SYSTEM_ID); -// fail("SAXException is not thrown"); -// } catch(org.xml.sax.SAXException se) { -// //expected -// } -// } -// -// try { -// MyDefaultHandler dh = new MyDefaultHandler(); -// parser.parse((InputStream) null, dh, -// SAXParserTestSupport.XML_SYSTEM_ID); -// fail("java.lang.IllegalArgumentException is not thrown"); -// } catch(java.lang.IllegalArgumentException iae) { -// //expected -// } -// -// try { -// InputStream is = new FileInputStream(list_wf[0]); -// parser.parse(is, (DefaultHandler) null, -// SAXParserTestSupport.XML_SYSTEM_ID); -// } catch(java.lang.IllegalArgumentException iae) { -// fail("java.lang.IllegalArgumentException is thrown"); -// } -// -// // TODO commented out since our parser is nonvalidating and thus never -// // tries to load staff.dtd in "/" ... and therefore never can fail with -// // an IOException -// /*try { -// MyDefaultHandler dh = new MyDefaultHandler(); -// InputStream is = new FileInputStream(list_wf[0]); -// parser.parse(is, dh, "/"); -// fail("Expected IOException was not thrown"); -// } catch(IOException ioe) { -// // expected -// }*/ - } - - public void testParseInputStreamHandlerBase() throws Exception { - for(int i = 0; i < list_wf.length; i++) { - HashMap<String, String> hm = sp.readFile(list_out_hb[i].getPath()); - MyHandler dh = new MyHandler(); - InputStream is = new FileInputStream(list_wf[i]); - parser.parse(is, dh); - assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData())); - } - - for (File file : list_nwf) { - try { - MyHandler dh = new MyHandler(); - InputStream is = new FileInputStream(file); - parser.parse(is, dh); - fail("SAXException is not thrown"); - } catch (SAXException expected) { - } - } - - try { - MyHandler dh = new MyHandler(); - parser.parse((InputStream) null, dh); - fail("java.lang.IllegalArgumentException is not thrown"); - } catch (IllegalArgumentException expected) { - } - - InputStream is = new FileInputStream(list_wf[0]); - parser.parse(is, (HandlerBase) null); - - // Inject IOException - try { - is = new BrokenInputStream(new FileInputStream(list_wf[0]), 10); - parser.parse(is, (HandlerBase) null); - fail("IOException expected"); - } catch(IOException e) { - // Expected - } finally { - is.close(); - } - } - - public void testParseInputStreamHandlerBaseString() throws Exception { - for(int i = 0; i < list_wf.length; i++) { - HashMap<String, String> hm = sp.readFile(list_out_hb[i].getPath()); - MyHandler dh = new MyHandler(); - InputStream is = new FileInputStream(list_wf[i]); - parser.parse(is, dh, SAXParserTestSupport.XML_SYSTEM_ID); - assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData())); - } - - for (File file : list_nwf) { - try { - MyHandler dh = new MyHandler(); - InputStream is = new FileInputStream(file); - parser.parse(is, dh, SAXParserTestSupport.XML_SYSTEM_ID); - fail("SAXException is not thrown"); - } catch (SAXException expected) { - } - } - - try { - MyHandler dh = new MyHandler(); - parser.parse(null, dh, SAXParserTestSupport.XML_SYSTEM_ID); - fail("java.lang.IllegalArgumentException is not thrown"); - } catch(IllegalArgumentException expected) { - } - - InputStream is = new FileInputStream(list_wf[0]); - parser.parse(is, (HandlerBase) null, SAXParserTestSupport.XML_SYSTEM_ID); - - // Inject IOException - try { - is = new BrokenInputStream(new FileInputStream(list_wf[0]), 10); - parser.parse(is, (HandlerBase) null, SAXParserTestSupport.XML_SYSTEM_ID); - fail("IOException expected"); - } catch(IOException expected) { - } finally { - is.close(); - } - } - - /** - * @test javax.xml.parsers.SAXParser#parse(java.lang.String, - * org.xml.sax.helpers.DefaultHandler) - */ - public void test_parseLjava_lang_StringLorg_xml_sax_helpers_DefaultHandler() - throws Exception { - - for(int i = 0; i < list_wf.length; i++) { - - HashMap<String, String> hm = new SAXParserTestSupport().readFile( - list_out_dh[i].getPath()); - MyDefaultHandler dh = new MyDefaultHandler(); - parser.parse(list_wf[i].toURI().toString(), dh); - assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData())); - } - - for(int i = 0; i < list_nwf.length; i++) { - try { - MyDefaultHandler dh = new MyDefaultHandler(); - parser.parse(list_nwf[i].toURI().toString(), dh); - fail("SAXException is not thrown"); - } catch(org.xml.sax.SAXException se) { - //expected - } - } - - try { - MyDefaultHandler dh = new MyDefaultHandler(); - parser.parse((String) null, dh); - fail("java.lang.IllegalArgumentException is not thrown"); - } catch(java.lang.IllegalArgumentException iae) { - //expected - } - - try { - parser.parse(list_wf[0].toURI().toString(), (DefaultHandler) null); - } catch(java.lang.IllegalArgumentException iae) { - fail("java.lang.IllegalArgumentException is thrown"); - } - } - - public void testParseStringHandlerBase() { - for(int i = 0; i < list_wf.length; i++) { - try { - HashMap<String, String> hm = sp.readFile( - list_out_hb[i].getPath()); - MyHandler dh = new MyHandler(); - parser.parse(list_wf[i].toURI().toString(), dh); - assertTrue(SAXParserTestSupport.equalsMaps(hm, - dh.createData())); - } catch (IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } catch (SAXException sax) { - fail("Unexpected SAXException " + sax.toString()); - } - } - - for(int i = 0; i < list_nwf.length; i++) { - try { - MyHandler dh = new MyHandler(); - parser.parse(list_nwf[i].toURI().toString(), dh); - fail("SAXException is not thrown"); - } catch(org.xml.sax.SAXException se) { - //expected - } catch (FileNotFoundException fne) { - fail("Unexpected FileNotFoundException " + fne.toString()); - } catch (IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } - } - - try { - MyHandler dh = new MyHandler(); - parser.parse((String) null, dh); - fail("java.lang.IllegalArgumentException is not thrown"); - } catch(java.lang.IllegalArgumentException iae) { - //expected - } catch (IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } catch(SAXException sax) { - fail("Unexpected SAXException " + sax.toString()); - } - - try { - parser.parse(list_wf[0].toURI().toString(), (HandlerBase) null); - } catch(java.lang.IllegalArgumentException iae) { - fail("java.lang.IllegalArgumentException is thrown"); - } catch (FileNotFoundException fne) { - fail("Unexpected FileNotFoundException " + fne.toString()); - } catch(IOException ioe) { - fail("Unexpected IOException " + ioe.toString()); - } catch(SAXException sax) { - fail("Unexpected SAXException " + sax.toString()); - } - } - - public void testReset() { - try { - spf = SAXParserFactory.newInstance(); - parser = spf.newSAXParser(); - - parser.setProperty(LEXICAL_HANDLER_PROPERTY, new MockHandler(new MethodLogger())); - parser.reset(); - assertEquals(null, parser.getProperty(LEXICAL_HANDLER_PROPERTY)); - } catch (Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testGetParser() { - spf = SAXParserFactory.newInstance(); - try { - Parser parser = spf.newSAXParser().getParser(); - assertNotNull(parser); - } catch (Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testGetReader() { - spf = SAXParserFactory.newInstance(); - try { - XMLReader reader = spf.newSAXParser().getXMLReader(); - assertNotNull(reader); - } catch (Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testSetGetProperty() { - // Ordinary case - String validName = "http://xml.org/sax/properties/lexical-handler"; - LexicalHandler validValue = new MockHandler(new MethodLogger()); - - try { - SAXParser parser = spf.newSAXParser(); - parser.setProperty(validName, validValue); - assertEquals(validValue, parser.getProperty(validName)); - - parser.setProperty(validName, null); - assertEquals(null, parser.getProperty(validName)); - } catch (Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - - // Unsupported property - try { - SAXParser parser = spf.newSAXParser(); - parser.setProperty("foo", "bar"); - fail("SAXNotRecognizedException expected"); - } catch (SAXNotRecognizedException e) { - // Expected - } catch (Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - - try { - SAXParser parser = spf.newSAXParser(); - parser.getProperty("foo"); - fail("SAXNotRecognizedException expected"); - } catch (SAXNotRecognizedException e) { - // Expected - } catch (Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - - // No name case - try { - SAXParser parser = spf.newSAXParser(); - parser.setProperty(null, "bar"); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - // Expected - } catch (Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - - try { - SAXParser parser = spf.newSAXParser(); - parser.getProperty(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - // Expected - } catch (Exception e) { - throw new RuntimeException("Unexpected exception", e); - } - } - -} diff --git a/luni/src/test/java/tests/api/javax/xml/parsers/SAXParserTestSupport.java b/luni/src/test/java/tests/api/javax/xml/parsers/SAXParserTestSupport.java deleted file mode 100644 index 2b7e1da..0000000 --- a/luni/src/test/java/tests/api/javax/xml/parsers/SAXParserTestSupport.java +++ /dev/null @@ -1,492 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.javax.xml.parsers; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; - -import org.xml.sax.Attributes; -import org.xml.sax.HandlerBase; -import org.xml.sax.InputSource; -import org.xml.sax.Locator; -import org.xml.sax.SAXParseException; -import org.xml.sax.helpers.DefaultHandler; - -/** - * Support for SAXParserTest. Shares the element keys used in the golden files. - * Compares the result of the parser with golden data. - * Contains the handler classes used to track the output of the parser. - */ -class SAXParserTestSupport { - - public static final char SEPARATOR_ELEMENT = '^'; - public static final char SEPARATOR_STRING = '$'; - public static final char SEPARATOR_DATA = '#'; - - public static final String XML_WF = "/wf/"; - public static final String XML_NWF = "/nwf/"; - - public static final String XML_WF_OUT_DH = "/out_dh/"; - public static final String XML_WF_OUT_HB = "/out_hb/"; - - public static final String XML_SYSTEM_ID = "." + "/systemid/"; - - public static final String KEY_IS_START_DOC = "isEndDocument"; - public static final String KEY_IS_END_DOC = "isStartDocument"; - public static final String KEY_TEXT = "text"; - public static final String KEY_ERROR = "error"; - public static final String KEY_FATAL_ERROR = "fatalError"; - public static final String KEY_WARNING = "warning"; - public static final String KEY_END_ELEMENT = "endElement"; - public static final String KEY_END_PREFIX_MAPPING = "endPrefixMapping"; - public static final String KEY_IGNORABLE_WHITE_SPACE = - "ignorableWhitespace"; - public static final String KEY_NOTATION_DECL = "notationDecl"; - public static final String KEY_PROCESSING_INSTRUCTION = - "processingInstruction"; - public static final String KEY_RESOLVE_ENTITY = "resolveEntity"; - public static final String KEY_DOCUMENT_LOCATORS = "documentLocators"; - public static final String KEY_SKIPPED_ENTITY = "skippedEntity"; - public static final String KEY_START_ELEMENT = "startElement"; - public static final String KEY_START_PREFIX_MAPPING = "startPrefixMapping"; - public static final String KEY_UNPARSED_ENTITY_DECL = "unparsedEntityDecl"; - - static String [] KEYS = {KEY_IS_START_DOC, KEY_IS_END_DOC, KEY_TEXT, - KEY_ERROR, KEY_FATAL_ERROR, KEY_WARNING, KEY_END_ELEMENT, - KEY_END_PREFIX_MAPPING, KEY_PROCESSING_INSTRUCTION, - KEY_SKIPPED_ENTITY, KEY_START_ELEMENT, - KEY_START_PREFIX_MAPPING}; - - static { - String tmp = System.getProperty("java.io.tmpdir", "."); - - new File(tmp).mkdirs(); - new File(tmp, XML_WF).mkdirs(); - new File(tmp, XML_NWF).mkdirs(); - new File(tmp, XML_WF_OUT_DH).mkdirs(); - new File(tmp, XML_WF_OUT_HB).mkdirs(); - } - - /** - * Initialize the SAXParserTest reference by filling in the data from the - * file passed to the method. This will be the reference to compare - * against with the output of the parser. - */ - public HashMap<String, String> readFile(String fileName) { - HashMap<String, String> storage = new HashMap<String, String>(); - try { - - InputStream is = new FileInputStream(fileName); - - int c = is.read(); - - StringBuffer str = new StringBuffer(); - int i = 0; - while(c != -1) { - if((char)c == SEPARATOR_DATA) { - // if(str.length() > 0) { - if(i < KEYS.length) { - storage.put(KEYS[i], str.toString()); - // System.out.println(str.toString()); - str.setLength(0); - i++; - } - // } - } else { - str.append((char)c); - } - try { - c = is.read(); - } catch (Exception e) { - c = -1; - } - } - try { - is.close(); - } catch (IOException e) { - } - - } catch(IOException ioe) { - System.out.println("IOException during processing the file: " - + fileName); - } - return storage; - } - - /** - * Compares the content of two HashMaps. One map should be the reference - * containing the correct string for each xml document element and the other - * should contain the elements filled with output from the parser. - * - * @param original the reference - * @param result the result of the parser - * @return true if they're equal. - */ - public static boolean equalsMaps(HashMap<String, String> original, - HashMap<String, String> result) { - - if(original == null && result == null) { - return true; - } else { - if(original.size() != result.size()) return false; - - for(int i = 0; i < KEYS.length; i++) { - if(!original.get(KEYS[i]).equals(result.get(KEYS[i]))) { - System.out.println("for "+KEYS[i]+": original:" + - original.get(KEYS[i])); - System.out.println(); - System.out.println(" result:" + result.get(KEYS[i])); - System.out.println(); - return false; - } - } - return true; - } - } - - static class MyDefaultHandler extends DefaultHandler { - - public StringBuffer data_isEndDocument = new StringBuffer(); - public StringBuffer data_isStartDocument = new StringBuffer(); - public StringBuffer data_text = new StringBuffer(); - public StringBuffer data_error = new StringBuffer(); - public StringBuffer data_fatalError = new StringBuffer(); - public StringBuffer data_warning = new StringBuffer(); - public StringBuffer data_endElement = new StringBuffer(); - public StringBuffer data_endPrefixMapping = new StringBuffer(); - public StringBuffer data_processingInstruction = new StringBuffer(); - public StringBuffer data_skippedEntity = new StringBuffer(); - public StringBuffer data_startElement = new StringBuffer(); - public StringBuffer data_startPrefixMapping = new StringBuffer(); - - public HashMap<String, String> createData() { - HashMap<String, String> hm = new HashMap<String, String>(); - hm.put(KEY_IS_END_DOC, data_isEndDocument.toString()); - hm.put(KEY_IS_START_DOC, data_isStartDocument.toString()); - hm.put(KEY_TEXT, data_text.toString()); - hm.put(KEY_ERROR, data_error.toString()); - hm.put(KEY_FATAL_ERROR, data_fatalError.toString()); - hm.put(KEY_WARNING, data_warning.toString()); - hm.put(KEY_END_ELEMENT, data_endElement.toString()); - hm.put(KEY_END_PREFIX_MAPPING, data_endPrefixMapping.toString()); - - hm.put(KEY_PROCESSING_INSTRUCTION, - data_processingInstruction.toString()); - hm.put(KEY_SKIPPED_ENTITY, data_skippedEntity.toString()); - hm.put(KEY_START_ELEMENT, data_startElement.toString()); - hm.put(KEY_START_PREFIX_MAPPING, - data_startPrefixMapping.toString()); - return hm; - } - - public void printMap() { - System.out.print(data_isStartDocument.toString() + SEPARATOR_DATA + - data_isEndDocument.toString() + SEPARATOR_DATA + - data_text.toString() + SEPARATOR_DATA + - data_error.toString()+ SEPARATOR_DATA + - data_fatalError.toString()+ SEPARATOR_DATA + - data_warning.toString()+ SEPARATOR_DATA + - data_endElement.toString() + SEPARATOR_DATA+ - data_endPrefixMapping.toString()+ SEPARATOR_DATA + - data_processingInstruction.toString() + SEPARATOR_DATA + - data_skippedEntity.toString() + SEPARATOR_DATA + - data_startElement.toString() + SEPARATOR_DATA + - data_startPrefixMapping.toString()+ SEPARATOR_DATA); - } - - @Override - public void characters(char[] ch, int start, int length) { - String str = new String(ch, start, length); - data_text.append(str); - // different sax parsers are allowed to handle chunking differently, - // therefore we cannot rely on identical chunks being delivered. - //data_text.append(ParsingSupport.SEPARATOR_ELEMENT); - } - - @Override - public void endDocument() { - data_isEndDocument.append(true); - data_isEndDocument.append(SEPARATOR_ELEMENT); - } - - @Override - public void endElement(String uri, String localName, String qName) { - StringBuffer sb = new StringBuffer(); - sb.append(uri); - sb.append(SEPARATOR_STRING); - sb.append(localName); - sb.append(SEPARATOR_STRING); - sb.append(qName); - data_endElement.append(sb); - data_endElement.append(SEPARATOR_ELEMENT); - } - - @Override - public void endPrefixMapping(String prefix) { - data_endPrefixMapping.append(prefix); - data_endPrefixMapping.append(SEPARATOR_ELEMENT); - } - - @Override - public void error(SAXParseException e) { - data_error.append(e); - data_error.append(SEPARATOR_ELEMENT); - } - - @Override - public void fatalError(SAXParseException e) { - data_fatalError.append(e); - data_fatalError.append(SEPARATOR_ELEMENT); - } - - @Override - public void ignorableWhitespace(char[] ch, int start, int length) { - /* String s = new String(ch, start, length); - ignorableWhitespace.append(s); - ignorableWhitespace.append(ParsingSupport.SEPARATOR_ELEMENT);*/ - } - - @Override - public void notationDecl(String name, String publicId, - String systemId) { - /* data_notationDecl.append(name + ParsingSupport.SEPARATOR_STRING + - publicId + ParsingSupport.SEPARATOR_STRING + - systemId + ParsingSupport.SEPARATOR_STRING); - data_notationDecl.append(ParsingSupport.SEPARATOR_ELEMENT);*/ - } - - @Override - public void processingInstruction(String target, String data) { - data_processingInstruction.append(target + SEPARATOR_STRING + data); - data_processingInstruction.append(SEPARATOR_ELEMENT); - } - - @Override - public InputSource resolveEntity(String publicId, String systemId) { - // data_resolveEntity.append(publicId + - // ParsingSupport.SEPARATOR_STRING + systemId); - // data_resolveEntity.append(ParsingSupport.SEPARATOR_ELEMENT); - return null; - } - - @Override - public void setDocumentLocator(Locator locator) { - // data_documentLocators.append(locator); - // data_documentLocators.append(ParsingSupport.SEPARATOR_ELEMENT); - } - - @Override - public void skippedEntity(String name) { - data_skippedEntity.append(name); - data_skippedEntity.append(SEPARATOR_ELEMENT); - } - - @Override - public void startDocument() { - data_isStartDocument.append(true); - data_isStartDocument.append(SEPARATOR_ELEMENT); - } - - @Override - public void startElement(String uri, String localName, String qName, - Attributes attributes) { - data_startElement.append(uri); - data_startElement.append(SEPARATOR_STRING); - data_startElement.append(localName); - data_startElement.append(SEPARATOR_STRING); - data_startElement.append(qName); - - for(int i = 0; i < attributes.getLength(); i ++) - data_startElement.append( - SEPARATOR_STRING +attributes.getQName(i) + - SEPARATOR_STRING + attributes.getValue(i)); - - data_isStartDocument.append(SEPARATOR_ELEMENT); - } - - @Override - public void startPrefixMapping(String prefix, String uri) { - data_startPrefixMapping.append(prefix + SEPARATOR_STRING + uri); - } - - @Override - public void unparsedEntityDecl(String name, String publicId, - String systemId, String notationName) { - // data_unparsedEntityDecl.append(name - // + ParsingSupport.SEPARATOR_STRING + publicId - // + ParsingSupport.SEPARATOR_STRING - // + systemId + ParsingSupport.SEPARATOR_STRING + notationName); - } - - @Override - public void warning(SAXParseException e) { - data_warning.append(e); - } - } - - @SuppressWarnings("deprecation") - static class MyHandler extends HandlerBase { - - public StringBuffer data_isEndDocument = new StringBuffer(); - public StringBuffer data_isStartDocument = new StringBuffer(); - public StringBuffer data_text = new StringBuffer(); - public StringBuffer data_error = new StringBuffer(); - public StringBuffer data_fatalError = new StringBuffer(); - public StringBuffer data_warning = new StringBuffer(); - public StringBuffer data_endElement = new StringBuffer(); - public StringBuffer data_endPrefixMapping = new StringBuffer(); - public StringBuffer data_processingInstruction = new StringBuffer(); - public StringBuffer data_skippedEntity = new StringBuffer(); - public StringBuffer data_startElement = new StringBuffer(); - public StringBuffer data_startPrefixMapping = new StringBuffer(); - - public void printMap() { - System.out.print(data_isStartDocument.toString() + SEPARATOR_DATA + - data_isEndDocument.toString() + SEPARATOR_DATA + - data_text.toString() + SEPARATOR_DATA + - data_error.toString()+ SEPARATOR_DATA + - data_fatalError.toString()+ SEPARATOR_DATA + - data_warning.toString()+ SEPARATOR_DATA + - data_endElement.toString() + SEPARATOR_DATA+ - data_endPrefixMapping.toString()+ SEPARATOR_DATA + - data_processingInstruction.toString() + SEPARATOR_DATA + - data_skippedEntity.toString() + SEPARATOR_DATA + - data_startElement.toString() + SEPARATOR_DATA + - data_startPrefixMapping.toString()+ SEPARATOR_DATA); - } - - public HashMap<String, String> createData() { - HashMap<String, String> hm = new HashMap<String, String>(); - hm.put(KEY_IS_END_DOC, data_isEndDocument.toString()); - hm.put(KEY_IS_START_DOC, data_isStartDocument.toString()); - hm.put(KEY_TEXT, data_text.toString()); - hm.put(KEY_ERROR, data_error.toString()); - hm.put(KEY_FATAL_ERROR, data_fatalError.toString()); - hm.put(KEY_WARNING, data_warning.toString()); - hm.put(KEY_END_ELEMENT, data_endElement.toString()); - hm.put(KEY_END_PREFIX_MAPPING, data_endPrefixMapping.toString()); - hm.put(KEY_PROCESSING_INSTRUCTION, - data_processingInstruction.toString()); - hm.put(KEY_SKIPPED_ENTITY, data_skippedEntity.toString()); - hm.put(KEY_START_ELEMENT, data_startElement.toString()); - hm.put(KEY_START_PREFIX_MAPPING, - data_startPrefixMapping.toString()); - return hm; - } - - @Override - public void characters(char[] ch, int start, int length) { - String str = new String(ch, start, length); - data_text.append(str); - // different sax parsers are allowed to handle chunking differently, - // therefore we cannot rely on identical chunks being delivered. - //data_text.append(ParsingSupport.SEPARATOR_ELEMENT); - } - - @Override - public void endDocument() { - data_isEndDocument.append(true); - data_isEndDocument.append(SEPARATOR_ELEMENT); - } - - public void endElement(String uri, String localName, String qName) { - StringBuffer sb = new StringBuffer(); - sb.append(uri); - sb.append(SEPARATOR_STRING); - sb.append(localName); - sb.append(SEPARATOR_STRING); - sb.append(qName); - data_endElement.append(sb); - data_endElement.append(SEPARATOR_ELEMENT); - } - - @Override - public void error(SAXParseException e) { - data_error.append(e); - data_error.append(SEPARATOR_ELEMENT); - } - - @Override - public void fatalError(SAXParseException e) { - data_fatalError.append(e); - data_fatalError.append(SEPARATOR_ELEMENT); - } - - @Override - public void ignorableWhitespace(char[] ch, int start, int length) { - - } - - @Override - public void notationDecl(String name, String publicId, - String systemId) { - - } - - @Override - public void processingInstruction(String target, String data) { - data_processingInstruction.append(target + SEPARATOR_STRING + data); - data_processingInstruction.append(SEPARATOR_ELEMENT); - } - - @Override - public InputSource resolveEntity(String publicId, String systemId) { - return null; - } - - @Override - public void setDocumentLocator(Locator locator) { - - } - - @Override - public void startDocument() { - data_isStartDocument.append(true); - data_isStartDocument.append(SEPARATOR_ELEMENT); - } - - public void startElement(String uri, String localName, String qName, - Attributes attributes) { - data_startElement.append(uri); - data_startElement.append(SEPARATOR_STRING); - data_startElement.append(localName); - data_startElement.append(SEPARATOR_STRING); - data_startElement.append(qName); - - for(int i = 0; i < attributes.getLength(); i ++) - data_startElement.append(SEPARATOR_STRING - + attributes.getQName(i) + - SEPARATOR_STRING + attributes.getValue(i)); - - data_isStartDocument.append(SEPARATOR_ELEMENT); - } - - @Override - public void unparsedEntityDecl(String name, String publicId, - String systemId, String notationName) { - - } - - @Override - public void warning(SAXParseException e) { - data_warning.append(e); - } - } -} diff --git a/luni/src/test/java/tests/api/org/apache/harmony/kernel/dalvik/ThreadsTest.java b/luni/src/test/java/tests/api/org/apache/harmony/kernel/dalvik/ThreadsTest.java deleted file mode 100644 index 19c6229..0000000 --- a/luni/src/test/java/tests/api/org/apache/harmony/kernel/dalvik/ThreadsTest.java +++ /dev/null @@ -1,285 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.apache.harmony.kernel.dalvik; - -import java.lang.reflect.Field; -import java.util.concurrent.CyclicBarrier; -import java.util.concurrent.TimeUnit; -import junit.framework.Assert; -import junit.framework.TestCase; -import sun.misc.Unsafe; - -/** - * Tests for the <code>park()</code> functionality of {@link Unsafe}. - */ -public class ThreadsTest extends TestCase { - private static Unsafe UNSAFE = null; - static { - /* - * Set up {@link #UNSAFE}. This subverts the access check to - * get the unique Unsafe instance. We can do this because - * there's no security manager installed when running the - * test. - */ - try { - Field field = Unsafe.class.getDeclaredField("THE_ONE"); - field.setAccessible(true); - - UNSAFE = (Unsafe) field.get(null); - } catch (NoSuchFieldException ex) { - throw new RuntimeException(ex); - } catch (IllegalAccessException ex) { - throw new RuntimeException(ex); - } - } - - /** Test the case where the park times out. */ - public void test_parkFor_1() throws Exception { - CyclicBarrier barrier = new CyclicBarrier(2); - Parker parker = new Parker(barrier, false, 500); - Thread parkerThread = new Thread(parker); - Thread waiterThread = - new Thread(new WaitAndUnpark(barrier, 1000, parkerThread)); - - parkerThread.start(); - waiterThread.start(); - parker.assertDurationIsInRange(500); - waiterThread.join(); - parkerThread.join(); - } - - /** Test the case where the unpark happens before the timeout. */ - public void test_parkFor_2() throws Exception { - CyclicBarrier barrier = new CyclicBarrier(2); - Parker parker = new Parker(barrier, false, 1000); - Thread parkerThread = new Thread(parker); - Thread waiterThread = - new Thread(new WaitAndUnpark(barrier, 300, parkerThread)); - - parkerThread.start(); - waiterThread.start(); - parker.assertDurationIsInRange(300); - waiterThread.join(); - parkerThread.join(); - } - - /** Test the case where the thread is preemptively unparked. */ - public void test_parkFor_3() throws Exception { - CyclicBarrier barrier = new CyclicBarrier(1); - Parker parker = new Parker(barrier, false, 1000); - Thread parkerThread = new Thread(parker); - - UNSAFE.unpark(parkerThread); - parkerThread.start(); - parker.assertDurationIsInRange(0); - parkerThread.join(); - } - - /** Test the case where the park times out. */ - public void test_parkUntil_1() throws Exception { - CyclicBarrier barrier = new CyclicBarrier(2); - Parker parker = new Parker(barrier, true, 500); - Thread parkerThread = new Thread(parker); - Thread waiterThread = - new Thread(new WaitAndUnpark(barrier, 1000, parkerThread)); - - parkerThread.start(); - waiterThread.start(); - parker.assertDurationIsInRange(500); - waiterThread.join(); - parkerThread.join(); - } - - /** Test the case where the unpark happens before the timeout. */ - public void test_parkUntil_2() throws Exception { - CyclicBarrier barrier = new CyclicBarrier(2); - Parker parker = new Parker(barrier, true, 1000); - Thread parkerThread = new Thread(parker); - Thread waiterThread = - new Thread(new WaitAndUnpark(barrier, 300, parkerThread)); - - parkerThread.start(); - waiterThread.start(); - parker.assertDurationIsInRange(300); - waiterThread.join(); - parkerThread.join(); - } - - /** Test the case where the thread is preemptively unparked. */ - public void test_parkUntil_3() throws Exception { - CyclicBarrier barrier = new CyclicBarrier(1); - Parker parker = new Parker(barrier, true, 1000); - Thread parkerThread = new Thread(parker); - - UNSAFE.unpark(parkerThread); - parkerThread.start(); - parker.assertDurationIsInRange(0); - parkerThread.join(); - } - - // TODO: Add more tests. - - /** - * Helper <code>Runnable</code> for tests, which parks for or until - * the indicated value, noting the duration of time actually parked. - */ - private static class Parker implements Runnable { - - private final CyclicBarrier barrier; - - /** whether {@link #amount} is milliseconds to wait in an - * absolute fashion (<code>true</code>) or nanoseconds to wait - * in a relative fashion (<code>false</code>) */ - private final boolean absolute; - - /** amount to wait (see above) */ - private final long amount; - - /** whether the run has completed */ - private boolean completed; - - /** recorded start time */ - private long startMillis; - - /** recorded end time */ - private long endMillis; - - /** - * Construct an instance. - * - * @param absolute whether to use an absolute time or not; in - * either case, this constructor takes a duration to park for - * @param parkMillis the number of milliseconds to be parked - */ - public Parker(CyclicBarrier barrier, boolean absolute, long parkMillis) { - this.barrier = barrier; - this.absolute = absolute; - - // Multiply by 1000000 because parkFor() takes nanoseconds. - this.amount = absolute ? parkMillis : parkMillis * 1000000; - } - - public void run() { - try { - barrier.await(60, TimeUnit.SECONDS); - } catch (Exception e) { - throw new AssertionError(e); - } - boolean absolute = this.absolute; - long amount = this.amount; - long startNanos = System.nanoTime(); - long start = System.currentTimeMillis(); - - if (absolute) { - UNSAFE.park(true, start + amount); - } else { - UNSAFE.park(false, amount); - } - - long endNanos = System.nanoTime(); - - synchronized (this) { - startMillis = startNanos / 1000000; - endMillis = endNanos / 1000000; - completed = true; - notifyAll(); - } - } - - /** - * Wait for the test to complete and return the duration. - * - * @param maxWaitMillis the maximum amount of time to - * wait for the test to complete - * @return the duration in milliseconds - */ - public long getDurationMillis(long maxWaitMillis) { - synchronized (this) { - if (! completed) { - try { - wait(maxWaitMillis); - } catch (InterruptedException ignored) { - } - if (! completed) { - Assert.fail("parker hung for more than " + maxWaitMillis + " ms"); - } - } - - return endMillis - startMillis; - } - } - - /** - * Asserts that the actual duration is within 10% of the - * given expected time. - * - * @param expectedMillis the expected duration, in milliseconds - */ - public void assertDurationIsInRange(long expectedMillis) { - /* - * Allow a bit more slop for the maximum on "expected - * instantaneous" results. - */ - long minimum = (long) ((double) expectedMillis * 0.90); - long maximum = - Math.max((long) ((double) expectedMillis * 1.10), 10); - long waitMillis = Math.max(expectedMillis * 10, 10); - long duration = getDurationMillis(waitMillis); - - if (duration < minimum) { - Assert.fail("expected duration: " + expectedMillis + - " minimum duration: " + minimum + - " actual duration too short: " + duration); - } else if (duration > maximum) { - Assert.fail("expected duration: " + expectedMillis + - " maximum duration: " + maximum + - " actual duration too long: " + duration); - } - } - } - - /** - * Helper <code>Runnable</code> for tests, which waits for the - * specified amount of time and then unparks an indicated thread. - */ - private static class WaitAndUnpark implements Runnable { - private final CyclicBarrier barrier; - private final long waitMillis; - private final Thread thread; - - public WaitAndUnpark(CyclicBarrier barrier, long waitMillis, Thread thread) { - this.barrier = barrier; - this.waitMillis = waitMillis; - this.thread = thread; - } - - public void run() { - try { - barrier.await(60, TimeUnit.SECONDS); - } catch (Exception e) { - throw new AssertionError(e); - } - try { - Thread.sleep(waitMillis); - } catch (InterruptedException ex) { - throw new RuntimeException("shouldn't happen", ex); - } - - UNSAFE.unpark(thread); - } - } -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/HandlerBaseTest.java b/luni/src/test/java/tests/api/org/xml/sax/HandlerBaseTest.java deleted file mode 100644 index 8dfe38b..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/HandlerBaseTest.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax; - -import junit.framework.TestCase; - -import org.xml.sax.AttributeList; -import org.xml.sax.HandlerBase; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; -import org.xml.sax.helpers.AttributeListImpl; -import org.xml.sax.helpers.LocatorImpl; - -@SuppressWarnings("deprecation") -public class HandlerBaseTest extends TestCase { - - /* - * Note: most of the tests have to check for an empty implementation of the - * respective methods and, as a result, are somewhat trivial. - */ - - private HandlerBase h = new HandlerBase(); - - public void testResolveEntity() { - try { - h.resolveEntity("publicID", "systemID"); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testNotationDecl() { - h.notationDecl("name", "publicID", "systemID"); - } - - public void testUnparsedEntityDecl() { - h.unparsedEntityDecl("name", "publicID", "systemID", "notationName"); - } - - public void testSetDocumentLocator() { - h.setDocumentLocator(new LocatorImpl()); - } - - public void testStartDocument() { - try { - h.startDocument(); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testEndDocument() { - try { - h.endDocument(); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testStartElement() { - try { - h.startElement("name", new AttributeListImpl()); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testEndElement() { - try { - h.endElement("name"); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testCharacters() { - try { - h.characters("The quick brown fox".toCharArray(), 4, 11); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testIgnorableWhitespace() { - try { - h.ignorableWhitespace(" ".toCharArray(), 4, 11); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testProcessingInstruction() { - try { - h.processingInstruction("target", "data"); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testWarning() { - try { - h.warning(new SAXParseException("Foo", new LocatorImpl())); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testError() { - try { - h.error(new SAXParseException("Foo", new LocatorImpl())); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testFatalError() { - // Ordinary case - try { - h.fatalError(new SAXParseException("Foo", new LocatorImpl())); - fail("SAXException expected"); - } catch (SAXException e) { - // Expected - } - - // No exception - try { - h.fatalError(null); - fail("NullPointerException expected"); - } catch (SAXException e) { - fail("NullPointerException expected"); - } catch (NullPointerException e) { - // Expected - } - - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/InputSourceTest.java b/luni/src/test/java/tests/api/org/xml/sax/InputSourceTest.java deleted file mode 100644 index f9040f0..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/InputSourceTest.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.io.Reader; -import java.io.StringReader; - -import junit.framework.TestCase; - -import org.xml.sax.InputSource; - -public class InputSourceTest extends TestCase { - - public void testInputSource() { - InputSource i = new InputSource(); - - assertNull(i.getByteStream()); - assertNull(i.getCharacterStream()); - assertNull(i.getEncoding()); - assertNull(i.getPublicId()); - assertNull(i.getSystemId()); - } - - public void testInputSourceString() { - InputSource i = new InputSource("Foo"); - - assertNull(i.getByteStream()); - assertNull(i.getCharacterStream()); - assertNull(i.getEncoding()); - assertNull(i.getPublicId()); - assertEquals("Foo", i.getSystemId()); - } - - public void testInputSourceInputStream() { - ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]); - - // Ordinary case - InputSource i = new InputSource(bais); - - assertEquals(bais, i.getByteStream()); - assertNull(i.getCharacterStream()); - assertNull(i.getEncoding()); - assertNull(i.getPublicId()); - assertNull(i.getSystemId()); - - // No input stream - i = new InputSource((InputStream)null); - - assertNull(i.getByteStream()); - assertNull(i.getCharacterStream()); - assertNull(i.getEncoding()); - assertNull(i.getPublicId()); - assertNull(i.getSystemId()); - } - - public void testInputSourceReader() { - StringReader sr = new StringReader("Hello, world."); - - // Ordinary case - InputSource i = new InputSource(sr); - - assertNull(i.getByteStream()); - assertEquals(sr, i.getCharacterStream()); - assertNull(i.getEncoding()); - assertNull(i.getPublicId()); - assertNull(i.getSystemId()); - - // No reader - i = new InputSource((Reader)null); - - assertNull(i.getByteStream()); - assertNull(i.getCharacterStream()); - assertNull(i.getEncoding()); - assertNull(i.getPublicId()); - assertNull(i.getSystemId()); - } - - public void testSetPublicIdGetPublicId() { - InputSource i = new InputSource(); - - i.setPublicId("Foo"); - assertEquals("Foo", i.getPublicId()); - - i.setPublicId(null); - assertNull(i.getPublicId()); - } - - public void testSetSystemIdGetSystemId() { - InputSource i = new InputSource(); - - i.setSystemId("Foo"); - assertEquals("Foo", i.getSystemId()); - - i.setSystemId(null); - assertNull(i.getSystemId()); - } - - public void testSetByteStreamGetByteStream() { - ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]); - - InputSource i = new InputSource(); - - // Ordinary case - i.setByteStream(bais); - - assertEquals(bais, i.getByteStream()); - - // No input stream - i.setByteStream(null); - - assertNull(i.getByteStream()); - } - - public void testSetEncodingGetEncoding() { - InputSource i = new InputSource(); - - // Ordinary case - i.setEncoding("Klingon"); - - assertEquals("Klingon", i.getEncoding()); - - // No encoding - i.setEncoding(null); - - assertNull(i.getEncoding()); - } - - public void testSetCharacterStreamGetCharacterStream() { - StringReader sr = new StringReader("Hello, world."); - - InputSource i = new InputSource(); - - // Ordinary case - i.setCharacterStream(sr); - - assertNull(i.getByteStream()); - assertEquals(sr, i.getCharacterStream()); - assertNull(i.getEncoding()); - assertNull(i.getPublicId()); - assertNull(i.getSystemId()); - - // No reader - i.setCharacterStream(null); - - assertNull(i.getByteStream()); - assertNull(i.getCharacterStream()); - assertNull(i.getEncoding()); - assertNull(i.getPublicId()); - assertNull(i.getSystemId()); - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/SAXExceptionTest.java b/luni/src/test/java/tests/api/org/xml/sax/SAXExceptionTest.java deleted file mode 100644 index 11d00e7..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/SAXExceptionTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax; - -import junit.framework.TestCase; - -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; - -public class SAXExceptionTest extends TestCase { - - public static final String ERR = "Houston, we have a problem"; - - public void testSAXParseException() { - SAXException e = new SAXException(); - - assertNull(e.getMessage()); - assertNull(e.getException()); - } - - public void testSAXException_String_Exception() { - Exception c = new Exception(); - - // Ordinary case - SAXException e = new SAXException(ERR, c); - - assertEquals(ERR, e.getMessage()); - assertEquals(c, e.getException()); - - // No message - e = new SAXException(null, c); - - assertNull(e.getMessage()); - assertEquals(c, e.getException()); - - // No cause - e = new SAXParseException(ERR, null); - - assertEquals(ERR, e.getMessage()); - assertNull(e.getException()); - } - - public void testSAXException_String() { - // Ordinary case - SAXException e = new SAXException(ERR); - - assertEquals(ERR, e.getMessage()); - assertNull(e.getException()); - - // No message - e = new SAXException((String)null); - - assertNull(e.getMessage()); - assertNull(e.getException()); - } - - public void testSAXException_Exception() { - Exception c = new Exception(); - - // Ordinary case - SAXException e = new SAXException(c); - - assertNull(e.getMessage()); - assertEquals(c, e.getException()); - - // No cause - e = new SAXException((Exception)null); - - assertNull(e.getMessage()); - assertNull(e.getException()); - } - - public void testToString() { - // Ordinary case - SAXException e = new SAXException(ERR); - String s = e.toString(); - - assertTrue(s.contains(ERR)); - - // No message - e = new SAXException(); - s = e.toString(); - - assertFalse(s.contains(ERR)); - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/SAXNotRecognizedExceptionTest.java b/luni/src/test/java/tests/api/org/xml/sax/SAXNotRecognizedExceptionTest.java deleted file mode 100644 index 3c73b56..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/SAXNotRecognizedExceptionTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax; - -import junit.framework.TestCase; - -import org.xml.sax.SAXNotRecognizedException; - -public class SAXNotRecognizedExceptionTest extends TestCase { - - public static final String ERR = "Houston, we have a problem"; - - public void testSAXNotRecognizedException() { - SAXNotRecognizedException e = new SAXNotRecognizedException(); - assertNull(e.getMessage()); - } - - public void testSAXNotRecognizedException_String() { - SAXNotRecognizedException e = new SAXNotRecognizedException(ERR); - assertEquals(ERR, e.getMessage()); - - e = new SAXNotRecognizedException(null); - assertNull(e.getMessage()); - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/SAXNotSupportedExceptionTest.java b/luni/src/test/java/tests/api/org/xml/sax/SAXNotSupportedExceptionTest.java deleted file mode 100644 index 71ea455..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/SAXNotSupportedExceptionTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax; - -import junit.framework.TestCase; - -import org.xml.sax.SAXNotSupportedException; - -public class SAXNotSupportedExceptionTest extends TestCase { - - public static final String ERR = "Houston, we have a problem"; - - public void testSAXNotSupportedException() { - SAXNotSupportedException e = new SAXNotSupportedException(); - assertNull(e.getMessage()); - } - - public void testSAXNotSupportedException_String() { - SAXNotSupportedException e = new SAXNotSupportedException(ERR); - assertEquals(ERR, e.getMessage()); - - e = new SAXNotSupportedException(null); - assertNull(e.getMessage()); - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/SAXParseExceptionTest.java b/luni/src/test/java/tests/api/org/xml/sax/SAXParseExceptionTest.java deleted file mode 100644 index bfc48d4..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/SAXParseExceptionTest.java +++ /dev/null @@ -1,216 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax; - -import junit.framework.TestCase; - -import org.xml.sax.Locator; -import org.xml.sax.SAXParseException; -import org.xml.sax.helpers.LocatorImpl; - -public class SAXParseExceptionTest extends TestCase { - - public static final String ERR = "Houston, we have a problem"; - - public static final String SYS = "mySystemID"; - - public static final String PUB = "myPublicID"; - - public static final int ROW = 1; - - public static final int COL = 2; - - public void testSAXParseException_String_Locator_Exception() { - LocatorImpl l = new LocatorImpl(); - l.setPublicId(PUB); - l.setSystemId(SYS); - l.setLineNumber(ROW); - l.setColumnNumber(COL); - - Exception c = new Exception(); - - // Ordinary case - SAXParseException e = new SAXParseException(ERR, l, c); - - assertEquals(ERR, e.getMessage()); - assertEquals(c, e.getException()); - - assertEquals(PUB, e.getPublicId()); - assertEquals(SYS, e.getSystemId()); - assertEquals(ROW, e.getLineNumber()); - assertEquals(COL, e.getColumnNumber()); - - // No message - e = new SAXParseException(null, l, c); - - assertNull(e.getMessage()); - assertEquals(c, e.getException()); - - assertEquals(PUB, e.getPublicId()); - assertEquals(SYS, e.getSystemId()); - assertEquals(ROW, e.getLineNumber()); - assertEquals(COL, e.getColumnNumber()); - - // No locator - e = new SAXParseException(ERR, null, c); - - assertEquals(ERR, e.getMessage()); - assertEquals(c, e.getException()); - - assertNull(e.getPublicId()); - assertNull(e.getSystemId()); - assertEquals(-1, e.getLineNumber()); - assertEquals(-1, e.getColumnNumber()); - - // No cause - e = new SAXParseException(ERR, l, null); - - assertEquals(ERR, e.getMessage()); - assertNull(e.getException()); - - assertEquals(PUB, e.getPublicId()); - assertEquals(SYS, e.getSystemId()); - assertEquals(ROW, e.getLineNumber()); - assertEquals(COL, e.getColumnNumber()); - } - - public void testSAXParseException_String_Locator() { - LocatorImpl l = new LocatorImpl(); - l.setPublicId(PUB); - l.setSystemId(SYS); - l.setLineNumber(ROW); - l.setColumnNumber(COL); - - // Ordinary case - SAXParseException e = new SAXParseException(ERR, l); - - assertEquals(ERR, e.getMessage()); - assertNull(e.getException()); - - assertEquals(PUB, e.getPublicId()); - assertEquals(SYS, e.getSystemId()); - assertEquals(ROW, e.getLineNumber()); - assertEquals(COL, e.getColumnNumber()); - - // No message - e = new SAXParseException(null, l); - - assertNull(e.getMessage()); - assertNull(e.getException()); - - assertEquals(PUB, e.getPublicId()); - assertEquals(SYS, e.getSystemId()); - assertEquals(ROW, e.getLineNumber()); - assertEquals(COL, e.getColumnNumber()); - - // No locator - e = new SAXParseException(ERR, null); - - assertEquals(ERR, e.getMessage()); - assertNull(e.getException()); - - assertNull(e.getPublicId()); - assertNull(e.getSystemId()); - assertEquals(-1, e.getLineNumber()); - assertEquals(-1, e.getColumnNumber()); - - } - - public void testSAXParseException_String_String_String_int_int_Exception() { - Exception c = new Exception(); - - // Ordinary case - SAXParseException e = new SAXParseException(ERR, PUB, SYS, ROW, COL, c); - - assertEquals(ERR, e.getMessage()); - assertEquals(c, e.getException()); - - assertEquals(PUB, e.getPublicId()); - assertEquals(SYS, e.getSystemId()); - assertEquals(ROW, e.getLineNumber()); - assertEquals(COL, e.getColumnNumber()); - - // No message - e = new SAXParseException(null, PUB, SYS, ROW, COL, c); - - assertNull(e.getMessage()); - assertEquals(c, e.getException()); - - assertEquals(PUB, e.getPublicId()); - assertEquals(SYS, e.getSystemId()); - assertEquals(ROW, e.getLineNumber()); - assertEquals(COL, e.getColumnNumber()); - - // No locator - e = new SAXParseException(ERR, null, null, -1, -1, c); - - assertEquals(ERR, e.getMessage()); - assertEquals(c, e.getException()); - - assertNull(e.getPublicId()); - assertNull(e.getSystemId()); - assertEquals(-1, e.getLineNumber()); - assertEquals(-1, e.getColumnNumber()); - - // No cause - e = new SAXParseException(ERR, PUB, SYS, ROW, COL, null); - - assertEquals(ERR, e.getMessage()); - assertNull(e.getException()); - - assertEquals(PUB, e.getPublicId()); - assertEquals(SYS, e.getSystemId()); - assertEquals(ROW, e.getLineNumber()); - assertEquals(COL, e.getColumnNumber()); - } - - public void testSAXParseException_String_String_String_int_int() { - // Ordinary case - SAXParseException e = new SAXParseException(ERR, PUB, SYS, ROW, COL); - - assertEquals(ERR, e.getMessage()); - assertNull(e.getException()); - - assertEquals(PUB, e.getPublicId()); - assertEquals(SYS, e.getSystemId()); - assertEquals(ROW, e.getLineNumber()); - assertEquals(COL, e.getColumnNumber()); - - // No message - e = new SAXParseException(null, PUB, SYS, ROW, COL); - - assertNull(e.getMessage()); - assertNull(e.getException()); - - assertEquals(PUB, e.getPublicId()); - assertEquals(SYS, e.getSystemId()); - assertEquals(ROW, e.getLineNumber()); - assertEquals(COL, e.getColumnNumber()); - - // No locator - e = new SAXParseException(ERR, null, null, -1, -1); - - assertEquals(ERR, e.getMessage()); - assertNull(e.getException()); - - assertNull(e.getPublicId()); - assertNull(e.getSystemId()); - assertEquals(-1, e.getLineNumber()); - assertEquals(-1, e.getColumnNumber()); - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/ext/Attributes2ImplTest.java b/luni/src/test/java/tests/api/org/xml/sax/ext/Attributes2ImplTest.java deleted file mode 100644 index 348bef5..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/ext/Attributes2ImplTest.java +++ /dev/null @@ -1,392 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.ext; - -import junit.framework.TestCase; - -import org.xml.sax.Attributes; -import org.xml.sax.ext.Attributes2Impl; -import org.xml.sax.helpers.AttributesImpl; - -public class Attributes2ImplTest extends TestCase { - - // Note: The original SAX2 implementation of Attributes2Impl is - // severely broken. Thus all of these tests will probably fail - // unless the Android implementation of the class gets fixed. - - private Attributes2Impl empty = new Attributes2Impl(); - - private Attributes2Impl multi = new Attributes2Impl(); - - private Attributes2Impl cdata = new Attributes2Impl(); - - @Override - public void setUp() { - multi.addAttribute("http://some.uri", "foo", "ns1:foo", - "string", "abc"); - multi.addAttribute("http://some.uri", "bar", "ns1:bar", - "string", "xyz"); - multi.addAttribute("http://some.other.uri", "answer", "ns2:answer", - "int", "42"); - multi.addAttribute("http://yet.another.uri", "gabba", "ns3:gabba", - "string", "gabba"); - - multi.setDeclared(0, false); - multi.setSpecified(0, false); - - multi.setDeclared(1, true); - multi.setSpecified(1, false); - - multi.setDeclared(2, false); - multi.setSpecified(2, true); - - multi.setDeclared(3, true); - multi.setSpecified(3, true); - - cdata.addAttribute("http://yet.another.uri", "hey", "ns3:hey", - "CDATA", "hey"); - } - - public void testSetAttributes() { - // Ordinary case with Attributes2Impl - Attributes2Impl attrs = new Attributes2Impl(); - attrs.addAttribute("", "", "john", "string", "doe"); - - attrs.setAttributes(empty); - assertEquals(0, attrs.getLength()); - - attrs.setAttributes(multi); - for (int i = 0; i < multi.getLength(); i++) { - assertEquals(multi.getURI(i), attrs.getURI(i)); - assertEquals(multi.getLocalName(i), attrs.getLocalName(i)); - assertEquals(multi.getQName(i), attrs.getQName(i)); - assertEquals(multi.getType(i), attrs.getType(i)); - assertEquals(multi.getValue(i), attrs.getValue(i)); - assertEquals(multi.isDeclared(i), attrs.isDeclared(i)); - assertEquals(multi.isSpecified(i), attrs.isSpecified(i)); - } - - attrs.setAttributes(empty); - assertEquals(0, attrs.getLength()); - - // Ordinary case with AttributesImpl - attrs.setAttributes(new AttributesImpl(multi)); - assertEquals(multi.getLength(), attrs.getLength()); - - for (int i = 0; i < multi.getLength(); i++) { - assertEquals(multi.getURI(i), attrs.getURI(i)); - assertEquals(multi.getLocalName(i), attrs.getLocalName(i)); - assertEquals(multi.getQName(i), attrs.getQName(i)); - assertEquals(multi.getType(i), attrs.getType(i)); - assertEquals(multi.getValue(i), attrs.getValue(i)); - assertEquals(true, attrs.isDeclared(i)); - assertEquals(true, attrs.isSpecified(i)); - } - - // Special case with CDATA - attrs.setAttributes(new AttributesImpl(cdata)); - assertEquals(1, attrs.getLength()); - assertEquals(false, attrs.isDeclared(0)); - assertEquals(true, attrs.isSpecified(0)); - - // null case - try { - attrs.setAttributes(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - // Expected - } - } - - public void testAddAttribute() { - Attributes2Impl attrs = new Attributes2Impl(); - - // Ordinary case - attrs.addAttribute("http://yet.another.uri", "doe", "john:doe", - "string", "abc"); - - assertEquals(1, attrs.getLength()); - - assertEquals("http://yet.another.uri", attrs.getURI(0)); - assertEquals("doe", attrs.getLocalName(0)); - assertEquals("john:doe", attrs.getQName(0)); - assertEquals("string", attrs.getType(0)); - assertEquals("abc", attrs.getValue(0)); - - assertEquals(true, attrs.isDeclared(0)); - assertEquals(true, attrs.isSpecified(0)); - - // CDATA case - attrs.addAttribute("http://yet.another.uri", "doe", "jane:doe", - "CDATA", "abc"); - - assertEquals(2, attrs.getLength()); - - assertEquals("http://yet.another.uri", attrs.getURI(1)); - assertEquals("doe", attrs.getLocalName(1)); - assertEquals("jane:doe", attrs.getQName(1)); - assertEquals("CDATA", attrs.getType(1)); - assertEquals("abc", attrs.getValue(1)); - - assertEquals(false, attrs.isDeclared(1)); - assertEquals(true, attrs.isSpecified(1)); - } - - public void testRemoveAttribute() { - Attributes2Impl attrs = new Attributes2Impl(multi); - - // Ordinary case - attrs.removeAttribute(1); - - assertEquals(3, attrs.getLength()); - - assertEquals(multi.getURI(0), attrs.getURI(0)); - assertEquals(multi.getLocalName(0), attrs.getLocalName(0)); - assertEquals(multi.getQName(0), attrs.getQName(0)); - assertEquals(multi.getType(0), attrs.getType(0)); - assertEquals(multi.getValue(0), attrs.getValue(0)); - assertEquals(multi.isDeclared(0), attrs.isDeclared(0)); - assertEquals(multi.isSpecified(0), attrs.isSpecified(0)); - - assertEquals(multi.getURI(2), attrs.getURI(1)); - assertEquals(multi.getLocalName(2), attrs.getLocalName(1)); - assertEquals(multi.getQName(2), attrs.getQName(1)); - assertEquals(multi.getType(2), attrs.getType(1)); - assertEquals(multi.getValue(2), attrs.getValue(1)); - assertEquals(multi.isDeclared(2), attrs.isDeclared(1)); - assertEquals(multi.isSpecified(2), attrs.isSpecified(1)); - - // Out of range - try { - attrs.removeAttribute(-1); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - - try { - attrs.removeAttribute(3); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - } - - public void testAttributes2Impl() { - assertEquals(0, empty.getLength()); - } - - public void testAttributes2ImplAttributes() { - // Ordinary case with Attributes2Impl - Attributes2Impl attrs = new Attributes2Impl(multi); - assertEquals(multi.getLength(), attrs.getLength()); - - for (int i = 0; i < multi.getLength(); i++) { - assertEquals(multi.getURI(i), attrs.getURI(i)); - assertEquals(multi.getLocalName(i), attrs.getLocalName(i)); - assertEquals(multi.getQName(i), attrs.getQName(i)); - assertEquals(multi.getType(i), attrs.getType(i)); - assertEquals(multi.getValue(i), attrs.getValue(i)); - assertEquals(multi.isDeclared(i), attrs.isDeclared(i)); - assertEquals(multi.isSpecified(i), attrs.isSpecified(i)); - } - - attrs = new Attributes2Impl(empty); - assertEquals(0, attrs.getLength()); - - // Ordinary case with AttributesImpl - attrs = new Attributes2Impl(new AttributesImpl(multi)); - assertEquals(multi.getLength(), attrs.getLength()); - - for (int i = 0; i < multi.getLength(); i++) { - assertEquals(multi.getURI(i), attrs.getURI(i)); - assertEquals(multi.getLocalName(i), attrs.getLocalName(i)); - assertEquals(multi.getQName(i), attrs.getQName(i)); - assertEquals(multi.getType(i), attrs.getType(i)); - assertEquals(multi.getValue(i), attrs.getValue(i)); - assertEquals(true, attrs.isDeclared(i)); - assertEquals(true, attrs.isSpecified(i)); - } - - // Special case with CDATA - attrs = new Attributes2Impl(new AttributesImpl(cdata)); - assertEquals(1, attrs.getLength()); - assertEquals(false, attrs.isDeclared(0)); - assertEquals(true, attrs.isSpecified(0)); - - // null case - try { - attrs = new Attributes2Impl(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - // Expected - } - } - - public void testIsDeclaredInt() { - // Ordinary cases - assertEquals(false, multi.isDeclared(0)); - assertEquals(true, multi.isDeclared(1)); - - // Out of range - try { - multi.isDeclared(-1); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - - try { - multi.isDeclared(4); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - } - - public void testIsDeclaredStringString() { - // Ordinary cases - assertEquals(false, multi.isDeclared("http://some.uri", "foo")); - assertEquals(true, multi.isDeclared("http://some.uri", "bar")); - - // Not found - try { - assertFalse(multi.isDeclared("not", "found")); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - // Expected - } - } - - public void testIsDeclaredString() { - // Ordinary cases - assertEquals(false, multi.isDeclared("ns1:foo")); - assertEquals(true, multi.isDeclared("ns1:bar")); - - // Not found - try { - assertFalse(multi.isDeclared("notfound")); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - // Expected - } - } - - public void testIsSpecifiedInt() { - // Ordinary cases - assertEquals(false, multi.isSpecified(1)); - assertEquals(true, multi.isSpecified(2)); - - // Out of range - try { - multi.isSpecified(-1); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - - try { - multi.isSpecified(4); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - } - - public void testIsSpecifiedStringString() { - // Ordinary cases - assertEquals(false, multi.isSpecified("http://some.uri", "bar")); - assertEquals(true, multi.isSpecified("http://some.other.uri", "answer")); - - // Not found - try { - assertFalse(multi.isSpecified("not", "found")); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - // Expected - } - } - - public void testIsSpecifiedString() { - // Ordinary cases - assertEquals(false, multi.isSpecified("ns1:bar")); - assertEquals(true, multi.isSpecified("ns2:answer")); - - // Not found - try { - assertFalse(multi.isSpecified("notfound")); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - // Expected - } - } - - public void testSetDeclared() { - // Ordinary cases - multi.setSpecified(0, false); - assertEquals(false, multi.isSpecified(0)); - - multi.setSpecified(0, true); - assertEquals(true, multi.isSpecified(0)); - - multi.setSpecified(0, false); - assertEquals(false, multi.isSpecified(0)); - - // Out of range - try { - multi.setSpecified(-1, true); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - - try { - multi.setSpecified(5, true); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - } - - public void testSetSpecified() { - // Ordinary cases - multi.setSpecified(0, false); - assertEquals(false, multi.isSpecified(0)); - - multi.setSpecified(0, true); - assertEquals(true, multi.isSpecified(0)); - - multi.setSpecified(0, false); - assertEquals(false, multi.isSpecified(0)); - - // Out of range - try { - multi.setSpecified(-1, true); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - - try { - multi.setSpecified(5, true); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/ext/DefaultHandler2Test.java b/luni/src/test/java/tests/api/org/xml/sax/ext/DefaultHandler2Test.java deleted file mode 100644 index 0e6c245..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/ext/DefaultHandler2Test.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.ext; - -import junit.framework.TestCase; - -import org.xml.sax.SAXException; -import org.xml.sax.ext.DefaultHandler2; - -import java.io.IOException; - -public class DefaultHandler2Test extends TestCase { - - private DefaultHandler2 h = new DefaultHandler2(); - - public void testDefaultHandler2() { - new DefaultHandler2(); - } - - public void testStartCDATA() { - try { - h.startCDATA(); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testEndCDATA() { - try { - h.endCDATA(); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testStartDTD() { - try { - h.startDTD("name", "publicId", "systemId"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testEndDTD() { - try { - h.endDTD(); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testStartEntity() { - try { - h.startEntity("name"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testEndEntity() { - try { - h.endEntity("name"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testComment() { - try { - h.comment("<!-- Comment -->".toCharArray(), 0, 15); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testAttributeDecl() { - try { - h.attributeDecl("eName", "aName", "type", "mode", "value"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testElementDecl() { - try { - h.elementDecl("name", "model"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testExternalEntityDecl() { - try { - h.externalEntityDecl("name", "publicId", "systemId"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testInternalEntityDecl() { - try { - h.internalEntityDecl("name", "value"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testGetExternalSubset() { - try { - assertNull(h.getExternalSubset("name", "http://some.uri")); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } catch (IOException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testResolveEntityStringString() { - try { - assertNull(h.resolveEntity("publicId", "systemId")); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } catch (IOException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testResolveEntityStringStringStringString() { - try { - assertNull(h.resolveEntity("name", "publicId", "http://some.uri", - "systemId")); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } catch (IOException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/ext/Locator2ImplTest.java b/luni/src/test/java/tests/api/org/xml/sax/ext/Locator2ImplTest.java deleted file mode 100644 index dbed1de..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/ext/Locator2ImplTest.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.ext; - -import junit.framework.TestCase; - -import org.xml.sax.Locator; -import org.xml.sax.ext.Locator2Impl; -import org.xml.sax.helpers.LocatorImpl; - -public class Locator2ImplTest extends TestCase { - - public static final String SYS = "mySystemID"; - - public static final String PUB = "myPublicID"; - - public static final int ROW = 1; - - public static final int COL = 2; - - public static final String ENC = "Klingon"; - - public static final String XML = "1.0"; - - public void testLocatorImpl() { - Locator2Impl l = new Locator2Impl(); - - assertEquals(null, l.getPublicId()); - assertEquals(null, l.getSystemId()); - assertEquals(0, l.getLineNumber()); - assertEquals(0, l.getColumnNumber()); - - assertEquals(null, l.getEncoding()); - assertEquals(null, l.getXMLVersion()); - } - - public void testLocatorImplLocator() { - Locator2Impl inner = new Locator2Impl(); - - inner.setPublicId(PUB); - inner.setSystemId(SYS); - inner.setLineNumber(ROW); - inner.setColumnNumber(COL); - - inner.setEncoding(ENC); - inner.setXMLVersion(XML); - - // Ordinary case - Locator2Impl outer = new Locator2Impl(inner); - - assertEquals(PUB, outer.getPublicId()); - assertEquals(SYS, outer.getSystemId()); - assertEquals(ROW, outer.getLineNumber()); - assertEquals(COL, outer.getColumnNumber()); - - assertEquals(ENC, outer.getEncoding()); - assertEquals(XML, outer.getXMLVersion()); - - // Instance of old locator - outer = new Locator2Impl(new LocatorImpl(inner)); - - assertEquals(PUB, outer.getPublicId()); - assertEquals(SYS, outer.getSystemId()); - assertEquals(ROW, outer.getLineNumber()); - assertEquals(COL, outer.getColumnNumber()); - - assertEquals(null, outer.getEncoding()); - assertEquals(null, outer.getXMLVersion()); - - // No locator - try { - outer = new Locator2Impl(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - // Expected - } - } - - public void testSetXMLVersionGetXMLVersion() { - Locator2Impl l = new Locator2Impl(); - - l.setXMLVersion(XML); - assertEquals(XML, l.getXMLVersion()); - - l.setXMLVersion(null); - assertEquals(null, l.getXMLVersion()); - } - - public void testSetEncodingGetEncoding() { - Locator2Impl l = new Locator2Impl(); - - l.setEncoding(ENC); - assertEquals(ENC, l.getEncoding()); - - l.setEncoding(null); - assertEquals(null, l.getEncoding()); - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/helpers/AttributeListImplTest.java b/luni/src/test/java/tests/api/org/xml/sax/helpers/AttributeListImplTest.java deleted file mode 100644 index 27f36ae..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/helpers/AttributeListImplTest.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.helpers; - -import junit.framework.TestCase; - -import org.xml.sax.AttributeList; -import org.xml.sax.helpers.AttributeListImpl; - -@SuppressWarnings("deprecation") -public class AttributeListImplTest extends TestCase { - - private AttributeListImpl empty = new AttributeListImpl(); - - private AttributeListImpl multi = new AttributeListImpl(); - - @Override - public void setUp() { - multi.addAttribute("foo", "string", "abc"); - multi.addAttribute("bar", "string", "xyz"); - multi.addAttribute("answer", "int", "42"); - } - - public void testAttributeListImpl() { - assertEquals(0, empty.getLength()); - assertEquals(3, multi.getLength()); - } - - public void testAttributeListImplAttributeList() { - // Ordinary case - AttributeListImpl ai = new AttributeListImpl(empty); - assertEquals(0, ai.getLength()); - - // Another ordinary case - ai = new AttributeListImpl(multi); - assertEquals(3, ai.getLength()); - - // No Attributes - try { - ai = new AttributeListImpl(null); - assertEquals(0, ai.getLength()); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - // Expected - } - } - - public void testSetAttributeList() { - // Ordinary cases - AttributeListImpl attrs = new AttributeListImpl(); - attrs.addAttribute("doe", "boolean", "false"); - - attrs.setAttributeList(empty); - assertEquals(0, attrs.getLength()); - - attrs.setAttributeList(multi); - assertEquals(multi.getLength(), attrs.getLength()); - - for (int i = 0; i < multi.getLength(); i++) { - assertEquals(multi.getName(i), attrs.getName(i)); - assertEquals(multi.getType(i), attrs.getType(i)); - assertEquals(multi.getValue(i), attrs.getValue(i)); - } - - // null case - try { - attrs.setAttributeList(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - // Expected, must still have old elements - assertEquals(3, attrs.getLength()); - } - } - - public void testAddAttribute() { - // Ordinary case - multi.addAttribute("doe", "boolean", "false"); - - assertEquals("doe", multi.getName(3)); - assertEquals("boolean", multi.getType(3)); - assertEquals("false", multi.getValue(3)); - - // Duplicate case - multi.addAttribute("doe", "boolean", "false"); - - assertEquals("doe", multi.getName(4)); - assertEquals("boolean", multi.getType(4)); - assertEquals("false", multi.getValue(4)); - - // null case - multi.addAttribute(null, null, null); - assertEquals(null, multi.getName(5)); - assertEquals(null, multi.getType(5)); - assertEquals(null, multi.getValue(5)); - } - - public void testRemoveAttribute() { - // Ordinary case - multi.removeAttribute("foo"); - assertEquals("bar", multi.getName(0)); - assertEquals("string", multi.getType(0)); - assertEquals("xyz", multi.getValue(0)); - - // Unknown attribute - multi.removeAttribute("john"); - assertEquals(2, multi.getLength()); - - // null case - multi.removeAttribute(null); - assertEquals(2, multi.getLength()); - } - - public void testClear() { - assertEquals(3, multi.getLength()); - multi.clear(); - assertEquals(0, multi.getLength()); - } - - public void testGetLength() { - AttributeListImpl ai = new AttributeListImpl(empty); - assertEquals(0, ai.getLength()); - - ai = new AttributeListImpl(multi); - assertEquals(3, ai.getLength()); - - for (int i = 2; i >= 0; i--) { - ai.removeAttribute(ai.getName(i)); - assertEquals(i, ai.getLength()); - } - } - - public void testGetName() { - // Ordinary cases - assertEquals("foo", multi.getName(0)); - assertEquals("bar", multi.getName(1)); - assertEquals("answer", multi.getName(2)); - - // Out of range - assertEquals(null, multi.getName(-1)); - assertEquals(null, multi.getName(3)); - } - - public void testGetTypeInt() { - // Ordinary cases - assertEquals("string", multi.getType(0)); - assertEquals("string", multi.getType(1)); - assertEquals("int", multi.getType(2)); - - // Out of range - assertEquals(null, multi.getType(-1)); - assertEquals(null, multi.getType(3)); - } - - public void testGetValueInt() { - // Ordinary cases - assertEquals("abc", multi.getValue(0)); - assertEquals("xyz", multi.getValue(1)); - assertEquals("42", multi.getValue(2)); - - // Out of range - assertEquals(null, multi.getValue(-1)); - assertEquals(null, multi.getValue(5)); - } - - public void testGetTypeString() { - // Ordinary cases - assertEquals("string", multi.getType("foo")); - assertEquals("string", multi.getType("bar")); - assertEquals("int", multi.getType("answer")); - - // Not found - assertEquals(null, multi.getType("john")); - - // null case - assertEquals(null, multi.getType(null)); - } - - public void testGetValueString() { - // Ordinary cases - assertEquals("abc", multi.getValue("foo")); - assertEquals("xyz", multi.getValue("bar")); - assertEquals("42", multi.getValue("answer")); - - // Not found - assertEquals(null, multi.getValue("john")); - - // null case - assertEquals(null, multi.getValue(null)); - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/helpers/AttributesImplTest.java b/luni/src/test/java/tests/api/org/xml/sax/helpers/AttributesImplTest.java deleted file mode 100644 index 1cc77ee..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/helpers/AttributesImplTest.java +++ /dev/null @@ -1,481 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.helpers; - -import junit.framework.TestCase; - -import org.xml.sax.Attributes; -import org.xml.sax.helpers.AttributesImpl; - -public class AttributesImplTest extends TestCase { - - private AttributesImpl empty = new AttributesImpl(); - - private AttributesImpl multi = new AttributesImpl(); - - @Override - public void setUp() { - multi.addAttribute("http://some.uri", "foo", "ns1:foo", - "string", "abc"); - multi.addAttribute("http://some.uri", "bar", "ns1:bar", - "string", "xyz"); - multi.addAttribute("http://some.other.uri", "answer", "ns2:answer", - "int", "42"); - - multi.addAttribute("", "gabbaHey", "", "string", "1-2-3-4"); - multi.addAttribute("", "", "gabba:hey", "string", "1-2-3-4"); - } - - public void testAttributesImpl() { - assertEquals(0, empty.getLength()); - assertEquals(5, multi.getLength()); - } - - public void testAttributesImplAttributes() { - // Ordinary case - AttributesImpl ai = new AttributesImpl(empty); - assertEquals(0, ai.getLength()); - - // Another ordinary case - ai = new AttributesImpl(multi); - assertEquals(5, ai.getLength()); - - // No Attributes - try { - ai = new AttributesImpl(null); - assertEquals(0, ai.getLength()); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - // Expected - } - } - - public void testGetLength() { - AttributesImpl ai = new AttributesImpl(empty); - assertEquals(0, ai.getLength()); - - ai = new AttributesImpl(multi); - assertEquals(5, ai.getLength()); - - for (int i = 4; i >= 0; i--) { - ai.removeAttribute(i); - assertEquals(i, ai.getLength()); - } - } - - public void testGetURI() { - // Ordinary cases - assertEquals("http://some.uri", multi.getURI(0)); - assertEquals("http://some.uri", multi.getURI(1)); - assertEquals("http://some.other.uri", multi.getURI(2)); - assertEquals("", multi.getURI(3)); - assertEquals("", multi.getURI(4)); - - // Out of range - assertEquals(null, multi.getURI(-1)); - assertEquals(null, multi.getURI(5)); - } - - public void testGetLocalName() { - // Ordinary cases - assertEquals("foo", multi.getLocalName(0)); - assertEquals("bar", multi.getLocalName(1)); - assertEquals("answer", multi.getLocalName(2)); - assertEquals("gabbaHey", multi.getLocalName(3)); - assertEquals("", multi.getLocalName(4)); - - // Out of range - assertEquals(null, multi.getLocalName(-1)); - assertEquals(null, multi.getLocalName(5)); - } - - public void testGetQName() { - // Ordinary cases - assertEquals("ns1:foo", multi.getQName(0)); - assertEquals("ns1:bar", multi.getQName(1)); - assertEquals("ns2:answer", multi.getQName(2)); - assertEquals("", multi.getQName(3)); - assertEquals("gabba:hey", multi.getQName(4)); - - // Out of range - assertEquals(null, multi.getQName(-1)); - assertEquals(null, multi.getQName(5)); - } - - public void testGetTypeInt() { - // Ordinary cases - assertEquals("string", multi.getType(0)); - assertEquals("string", multi.getType(1)); - assertEquals("int", multi.getType(2)); - assertEquals("string", multi.getType(3)); - assertEquals("string", multi.getType(4)); - - // Out of range - assertEquals(null, multi.getType(-1)); - assertEquals(null, multi.getType(5)); - } - - public void testGetValueInt() { - // Ordinary cases - assertEquals("abc", multi.getValue(0)); - assertEquals("xyz", multi.getValue(1)); - assertEquals("42", multi.getValue(2)); - assertEquals("1-2-3-4", multi.getValue(3)); - assertEquals("1-2-3-4", multi.getValue(4)); - - // Out of range - assertEquals(null, multi.getValue(-1)); - assertEquals(null, multi.getValue(5)); - } - - public void testGetIndexStringString() { - // Ordinary cases - assertEquals(0, multi.getIndex("http://some.uri", "foo")); - assertEquals(1, multi.getIndex("http://some.uri", "bar")); - assertEquals(2, multi.getIndex("http://some.other.uri", "answer")); - - // Not found - assertEquals(-1, multi.getIndex("john", "doe")); - - // null cases - assertEquals(-1, multi.getIndex("http://some.uri", null)); - assertEquals(-1, multi.getIndex(null, "foo")); - } - - public void testGetIndexString() { - // Ordinary cases - assertEquals(0, multi.getIndex("ns1:foo")); - assertEquals(1, multi.getIndex("ns1:bar")); - assertEquals(2, multi.getIndex("ns2:answer")); - assertEquals(4, multi.getIndex("gabba:hey")); - - // Not found - assertEquals(-1, multi.getIndex("john:doe")); - - // null case - assertEquals(-1, multi.getIndex(null)); - } - - public void testGetTypeStringString() { - // Ordinary cases - assertEquals("string", multi.getType("http://some.uri", "foo")); - assertEquals("string", multi.getType("http://some.uri", "bar")); - assertEquals("int", multi.getType("http://some.other.uri", "answer")); - - // Not found - assertEquals(null, multi.getType("john", "doe")); - - // null cases - assertEquals(null, multi.getType("http://some.uri", null)); - assertEquals(null, multi.getType(null, "foo")); - } - - public void testGetTypeString() { - // Ordinary cases - assertEquals("string", multi.getType("ns1:foo")); - assertEquals("string", multi.getType("ns1:bar")); - assertEquals("int", multi.getType("ns2:answer")); - assertEquals("string", multi.getType("gabba:hey")); - - // Not found - assertEquals(null, multi.getType("john:doe")); - - // null case - assertEquals(null, multi.getType(null)); - } - - public void testGetValueStringString() { - // Ordinary cases - assertEquals("abc", multi.getValue("http://some.uri", "foo")); - assertEquals("xyz", multi.getValue("http://some.uri", "bar")); - assertEquals("42", multi.getValue("http://some.other.uri", "answer")); - - // Not found - assertEquals(null, multi.getValue("john", "doe")); - - // null cases - assertEquals(null, multi.getValue("http://some.uri", null)); - assertEquals(null, multi.getValue(null, "foo")); - } - - public void testGetValueString() { - // Ordinary cases - assertEquals("abc", multi.getValue("ns1:foo")); - assertEquals("xyz", multi.getValue("ns1:bar")); - assertEquals("42", multi.getValue("ns2:answer")); - assertEquals("1-2-3-4", multi.getValue("gabba:hey")); - - // Not found - assertEquals(null, multi.getValue("john:doe")); - - // null case - assertEquals(null, multi.getValue(null)); - } - - public void testClear() { - assertEquals(5, multi.getLength()); - multi.clear(); - assertEquals(0, multi.getLength()); - } - - public void testSetAttributes() { - // Ordinary cases - AttributesImpl attrs = new AttributesImpl(); - attrs.addAttribute("http://yet.another.uri", "doe", "john:doe", - "boolean", "false"); - - attrs.setAttributes(empty); - assertEquals(0, attrs.getLength()); - - attrs.setAttributes(multi); - assertEquals(multi.getLength(), attrs.getLength()); - - for (int i = 0; i < multi.getLength(); i++) { - assertEquals(multi.getURI(i), attrs.getURI(i)); - assertEquals(multi.getLocalName(i), attrs.getLocalName(i)); - assertEquals(multi.getQName(i), attrs.getQName(i)); - assertEquals(multi.getType(i), attrs.getType(i)); - assertEquals(multi.getValue(i), attrs.getValue(i)); - } - - // null case - try { - attrs.setAttributes(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - // Expected, but must be empty now - assertEquals(0, attrs.getLength()); - } - } - - public void testAddAttribute() { - // Ordinary case - multi.addAttribute("http://yet.another.uri", "doe", "john:doe", - "boolean", "false"); - - assertEquals("http://yet.another.uri", multi.getURI(5)); - assertEquals("doe", multi.getLocalName(5)); - assertEquals("john:doe", multi.getQName(5)); - assertEquals("boolean", multi.getType(5)); - assertEquals("false", multi.getValue(5)); - - // Duplicate case - multi.addAttribute("http://yet.another.uri", "doe", "john:doe", - "boolean", "false"); - - assertEquals("http://yet.another.uri", multi.getURI(6)); - assertEquals("doe", multi.getLocalName(6)); - assertEquals("john:doe", multi.getQName(6)); - assertEquals("boolean", multi.getType(6)); - assertEquals("false", multi.getValue(6)); - - // null case - multi.addAttribute(null, null, null, null, null); - assertEquals(null, multi.getURI(7)); - assertEquals(null, multi.getLocalName(7)); - assertEquals(null, multi.getQName(7)); - assertEquals(null, multi.getType(7)); - assertEquals(null, multi.getValue(7)); - } - - public void testSetAttribute() { - // Ordinary case - multi.setAttribute(0, "http://yet.another.uri", "doe", "john:doe", - "boolean", "false"); - assertEquals("http://yet.another.uri", multi.getURI(0)); - assertEquals("doe", multi.getLocalName(0)); - assertEquals("john:doe", multi.getQName(0)); - assertEquals("boolean", multi.getType(0)); - assertEquals("false", multi.getValue(0)); - - // null case - multi.setAttribute(1, null, null, null, null, null); - assertEquals(null, multi.getURI(1)); - assertEquals(null, multi.getLocalName(1)); - assertEquals(null, multi.getQName(1)); - assertEquals(null, multi.getType(1)); - assertEquals(null, multi.getValue(1)); - - // Out of range - try { - multi.setAttribute(-1, "http://yet.another.uri", "doe", "john:doe", - "boolean", "false"); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - - try { - multi.setAttribute(5, "http://yet.another.uri", "doe", "john:doe", - "boolean", "false"); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - } - - public void testRemoveAttribute() { - // Ordinary case - multi.removeAttribute(0); - assertEquals("http://some.uri", multi.getURI(0)); - assertEquals("bar", multi.getLocalName(0)); - assertEquals("ns1:bar", multi.getQName(0)); - assertEquals("string", multi.getType(0)); - assertEquals("xyz", multi.getValue(0)); - - // Out of range - try { - multi.removeAttribute(-1); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - - try { - multi.removeAttribute(4); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - } - - public void testSetURI() { - // Ordinary case - multi.setURI(0, "http://yet.another.uri"); - assertEquals("http://yet.another.uri", multi.getURI(0)); - - // null case - multi.setURI(1, null); - assertEquals(null, multi.getURI(1)); - - // Out of range - try { - multi.setURI(-1, "http://yet.another.uri"); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - - try { - multi.setURI(5, "http://yet.another.uri"); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - } - - public void testSetLocalName() { - // Ordinary case - multi.setLocalName(0, "john"); - assertEquals("john", multi.getLocalName(0)); - - // null case - multi.setLocalName(1, null); - assertEquals(null, multi.getLocalName(1)); - - // Out of range - try { - multi.setLocalName(-1, "john"); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - - try { - multi.setLocalName(5, "john"); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - } - - public void testSetQName() { - // Ordinary case - multi.setQName(0, "john:doe"); - assertEquals("john:doe", multi.getQName(0)); - - // null case - multi.setQName(1, null); - assertEquals(null, multi.getQName(1)); - - // Out of range - try { - multi.setQName(-1, "john:doe"); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - - try { - multi.setQName(5, "john:doe"); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - } - - public void testSetType() { - // Ordinary case - multi.setType(0, "float"); - assertEquals("float", multi.getType(0)); - - // null case - multi.setType(1, null); - assertEquals(null, multi.getType(1)); - - // Out of range - try { - multi.setType(-1, "float"); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - - try { - multi.setType(5, "float"); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - } - - public void testSetValue() { - // Ordinary case - multi.setValue(0, "too much"); - assertEquals("too much", multi.getValue(0)); - - // null case - multi.setValue(1, null); - assertEquals(null, multi.getValue(1)); - - // Out of range - try { - multi.setValue(-1, "too much"); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - - try { - multi.setValue(5, "too much"); - fail("ArrayIndexOutOfBoundsException expected"); - } catch (ArrayIndexOutOfBoundsException e) { - // Expected - } - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/helpers/DefaultHandlerTest.java b/luni/src/test/java/tests/api/org/xml/sax/helpers/DefaultHandlerTest.java deleted file mode 100644 index a9530f2..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/helpers/DefaultHandlerTest.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.helpers; - -import junit.framework.TestCase; - -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; -import org.xml.sax.helpers.AttributesImpl; -import org.xml.sax.helpers.DefaultHandler; -import org.xml.sax.helpers.LocatorImpl; - -import java.io.IOException; - -public class DefaultHandlerTest extends TestCase { - - /* - * Note: most of the tests have to check for an empty implementation of the - * respective methods and, as a result, are somewhat trivial. - */ - - private DefaultHandler h = new DefaultHandler(); - - public void testResolveEntity() { - try { - h.resolveEntity("publicID", "systemID"); - } catch (SAXException e) { - throw new RuntimeException(e); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public void testNotationDecl() { - try { - h.notationDecl("name", "publicID", "systemID"); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testUnparsedEntityDecl() { - try { - h.unparsedEntityDecl("name", "publicID", "systemID", - "notationName"); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testSetDocumentLocator() { - h.setDocumentLocator(new LocatorImpl()); - } - - public void testStartDocument() { - try { - h.startDocument(); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testEndDocument() { - try { - h.endDocument(); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testStartPrefixMapping() { - try { - h.startPrefixMapping("prefix", "uri"); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testEndPrefixMapping() { - try { - h.endPrefixMapping("prefix"); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testStartElement() { - try { - h.startElement("uri", "name", "qname", new AttributesImpl()); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testEndElement() { - try { - h.endElement("uri", "name", "qname"); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testCharacters() { - try { - h.characters("The quick brown fox".toCharArray(), 4, 11); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testIgnorableWhitespace() { - try { - h.ignorableWhitespace(" ".toCharArray(), 4, 11); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testProcessingInstruction() { - try { - h.processingInstruction("target", "data"); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testSkippedEntity() { - try { - h.skippedEntity("name"); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testWarning() { - try { - h.warning(new SAXParseException("Foo", new LocatorImpl())); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testError() { - try { - h.error(new SAXParseException("Foo", new LocatorImpl())); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - - public void testFatalError() { - // Ordinary case - try { - h.fatalError(new SAXParseException("Foo", new LocatorImpl())); - fail("SAXException expected"); - } catch (SAXException e) { - // Expected - } - - // No exception - try { - h.fatalError(null); - fail("NullPointerException expected"); - } catch (SAXException e) { - fail("NullPointerException expected"); - } catch (NullPointerException e) { - // Expected - } - - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/helpers/LocatorImplTest.java b/luni/src/test/java/tests/api/org/xml/sax/helpers/LocatorImplTest.java deleted file mode 100644 index 8aa9c11..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/helpers/LocatorImplTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.helpers; - -import junit.framework.TestCase; - -import org.xml.sax.Locator; -import org.xml.sax.helpers.LocatorImpl; - -public class LocatorImplTest extends TestCase { - - public static final String SYS = "mySystemID"; - - public static final String PUB = "myPublicID"; - - public static final int ROW = 1; - - public static final int COL = 2; - - public void testLocatorImpl() { - LocatorImpl l = new LocatorImpl(); - - assertEquals(null, l.getPublicId()); - assertEquals(null, l.getSystemId()); - assertEquals(0, l.getLineNumber()); - assertEquals(0, l.getColumnNumber()); - } - - public void testLocatorImplLocator() { - LocatorImpl inner = new LocatorImpl(); - - inner.setPublicId(PUB); - inner.setSystemId(SYS); - inner.setLineNumber(ROW); - inner.setColumnNumber(COL); - - // Ordinary case - LocatorImpl outer = new LocatorImpl(inner); - - assertEquals(PUB, outer.getPublicId()); - assertEquals(SYS, outer.getSystemId()); - assertEquals(ROW, outer.getLineNumber()); - assertEquals(COL, outer.getColumnNumber()); - - // No locator - try { - outer = new LocatorImpl(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - // Expected - } - } - - public void testSetPublicIdGetPublicId() { - LocatorImpl l = new LocatorImpl(); - - l.setPublicId(PUB); - assertEquals(PUB, l.getPublicId()); - - l.setPublicId(null); - assertEquals(null, l.getPublicId()); - } - - public void testSetSystemIdGetSystemId() { - LocatorImpl l = new LocatorImpl(); - - l.setSystemId(SYS); - assertEquals(SYS, l.getSystemId()); - - l.setSystemId(null); - assertEquals(null, l.getSystemId()); - } - - public void testSetLineNumberGetLineNumber() { - LocatorImpl l = new LocatorImpl(); - - l.setLineNumber(ROW); - assertEquals(ROW, l.getLineNumber()); - - l.setLineNumber(0); - assertEquals(0, l.getLineNumber()); - } - - public void testSetColumnNumberGetColumnNumber() { - LocatorImpl l = new LocatorImpl(); - - l.setColumnNumber(COL); - assertEquals(COL, l.getColumnNumber()); - - l.setColumnNumber(0); - assertEquals(0, l.getColumnNumber()); - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/helpers/NamespaceSupportTest.java b/luni/src/test/java/tests/api/org/xml/sax/helpers/NamespaceSupportTest.java deleted file mode 100644 index 2f1ff8d..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/helpers/NamespaceSupportTest.java +++ /dev/null @@ -1,318 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.helpers; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.EmptyStackException; -import java.util.Enumeration; - -import junit.framework.TestCase; - -import org.xml.sax.helpers.NamespaceSupport; - -public class NamespaceSupportTest extends TestCase { - - final static String defaultUri = "http://www.android.com"; - final static String marketUri = "http://www.android.com/market"; - - NamespaceSupport ns; - ArrayList<String> expected; - - @Override - public void setUp() { - expected = new ArrayList<String>(); - expected.add("ak"); - expected.add("bk"); - - ns = new NamespaceSupport(); - ns.pushContext(); - - ns.declarePrefix("ak", marketUri); - ns.declarePrefix("bk", marketUri); - ns.declarePrefix("", defaultUri); - } - - @SuppressWarnings("unchecked") - public void testConstructor() { - String prefix; - boolean xmlPrefixExists = false; - - ns = new NamespaceSupport(); - Enumeration<String> prefixes = ns.getDeclaredPrefixes(); - - while (prefixes.hasMoreElements()) { - prefix = prefixes.nextElement(); - if (prefix.equals("xml")) xmlPrefixExists = true; - } - - assertTrue("Test 1: xml prefix does not exist.", xmlPrefixExists); - - // Check that only one context has been created by the constructor. - try { - ns.popContext(); - fail("Test 2: EmptyStackException expected."); - } catch (EmptyStackException e) { - // Expected. - } - } - - public void testPush_PopContext() { - int count; - - ns = new NamespaceSupport(); - count = countPrefixes(); - - ns.pushContext(); - ns.declarePrefix("dc", "http://www.purl.org/dc#"); - assertEquals("Test 1: Incorrect prefix count;", - count + 1, countPrefixes()); - - ns.popContext(); - assertEquals("Test 2: Incorrect prefix count;", - count, countPrefixes()); - - // Check that only one context has been created by pushContext(). - try { - ns.popContext(); - fail("Test 3: EmptyStackException expected."); - } catch (EmptyStackException e) { - // Expected. - } - } - - public void testReset() { - int count; - - ns = new NamespaceSupport(); - count = countPrefixes(); - - ns.pushContext(); - ns.declarePrefix("dc", "http://www.purl.org/dc#"); - - assertEquals("Test 1: Incorrect prefix count;", - count + 1, countPrefixes()); - - ns.reset(); - assertEquals("Test 2: Incorrect prefix count;", - count, countPrefixes()); - - // Check that only one context has been created by reset(). - try { - ns.popContext(); - fail("Test 3: EmptyStackException expected."); - } catch (EmptyStackException e) { - // Expected. - } - } - - public void testDeclare_GetPrefix() { - ns.pushContext(); - - // Part 1: Check that xml and xmlns are not accepted as prefixes. - assertFalse("Test 1: Invalid prefix accepted.", - ns.declarePrefix("xml", marketUri)); - - assertFalse("Test 2: Invalid prefix accepted.", - ns.declarePrefix("xmlns", marketUri)); - - // Part 2: Check that declarePrefix and getPrefix work for valid - // prefixes. - assertTrue("Test 3: Valid prefix not accepted.", - ns.declarePrefix("ak", marketUri)); - - assertTrue("Test 4: Incorrect prefix returned.", - ns.getPrefix(marketUri).equals("ak")); - - assertTrue("Test 5: Valid prefix not accepted.", - ns.declarePrefix("bk", marketUri)); - - assertTrue("Test 6: Incorrect prefix returned.", - expected.contains(ns.getPrefix(marketUri))); - - assertTrue("Test 7: Valid prefix not accepted.", - ns.declarePrefix("", defaultUri)); - - // Part 3: Negative Tests for getPrefix. - assertNull("Test 8: Non-null value returned for the URI that is " + - "assigned to the default namespace.", - ns.getPrefix(defaultUri)); - - assertNull("Test 9: Non-null value returned for an unassigned URI.", - ns.getPrefix(defaultUri + "/42")); - } - - @SuppressWarnings("unchecked") - public void testGetPrefixesLjava_lang_String() { - ArrayList<String> prefixes; - - prefixes = Collections.list(ns.getPrefixes(marketUri)); - assertTrue("Test 1: Incorrect set of prefixes returned.", - expected.containsAll(prefixes) && prefixes.containsAll(expected)); - - prefixes = Collections.list(ns.getPrefixes(defaultUri)); - assertTrue("Test 2: Default namespace prefix should not be returned.", - prefixes.size() == 0); - - prefixes = Collections.list(ns.getPrefixes(NamespaceSupport.XMLNS)); - assertTrue("Test 3: xml prefix is missing.", - prefixes.contains("xml") && prefixes.size() == 1); - - prefixes = Collections.list(ns.getPrefixes(defaultUri + "/42")); - assertTrue("Test 4: Non-empty enumeration returned for an unassigned URI.", - prefixes.size() == 0); - } - - @SuppressWarnings("unchecked") - public void testGetPrefixes() { - ArrayList<String> prefixes; - - expected.add("xml"); - - prefixes = Collections.list(ns.getPrefixes()); - assertTrue("Test 1: Incorrect set of prefixes returned.", - expected.containsAll(prefixes) && prefixes.containsAll(expected)); - } - - @SuppressWarnings("unchecked") - public void testGetDeclaredPrefixes() { - ArrayList<String> prefixes; - - expected.add(""); - - prefixes = Collections.list(ns.getDeclaredPrefixes()); - assertTrue("Test 1: Incorrect set of prefixes returned.", - expected.containsAll(prefixes) && prefixes.containsAll(expected)); - } - - public void testGetUri() { - assertEquals("Test 1: Incorrect URI returned;", - marketUri, ns.getURI("bk")); - assertEquals("Test 2: Incorrect URI returned;", - defaultUri, ns.getURI("")); - assertNull("Test 3: Null expected for not-existing prefix.", - ns.getURI("ck")); - - ns.popContext(); - assertNull("Test 4: Null expected for not-existing prefix.", - ns.getURI("bk")); - assertEquals("Test 5: Incorrect URI returned;", - NamespaceSupport.XMLNS, ns.getURI("xml")); - } - - public void testNamespaceDeclUris() { - - assertFalse("Test 1: Incorrect default value returned by isNamespaceDeclUris().", - ns.isNamespaceDeclUris()); - - try { - ns.setNamespaceDeclUris(true); - fail("Test 2: IllegalStateException expected since a context has already been pushed in setUp()."); - } catch (IllegalStateException e) { - // Expected. - } - - ns = new NamespaceSupport(); - ns.setNamespaceDeclUris(true); - assertTrue("Test 3: Incorrect value returned by isNamespaceDeclUris().", - ns.isNamespaceDeclUris()); - - ns.setNamespaceDeclUris(false); - assertFalse("Test 4: Incorrect value returned by isNamespaceDeclUris().", - ns.isNamespaceDeclUris()); - } - - public void testProcessName_Element() { - String[] parts = new String[3]; - - assertNotNull("Test 1: Non-null value expected.", - ns.processName("ak:hello", parts, false)); - assertEquals("Test 2: Incorrect namespace URI;", marketUri, parts[0]); - assertEquals("Test 3: Incorrect local name;", "hello", parts[1]); - assertEquals("Test 4: Incorrect raw name;", "ak:hello", parts[2]); - - assertNotNull("Test 5: Non-null value expected.", - ns.processName("bk:", parts, false)); - assertEquals("Test 6: Incorrect namespace URI;", marketUri, parts[0]); - assertEquals("Test 7: Incorrect local name;", "", parts[1]); - assertEquals("Test 8: Incorrect raw name;", "bk:", parts[2]); - - assertNotNull("Test 9: Non-null value expected.", - ns.processName("world", parts, false)); - assertEquals("Test 10: Incorrect namespace URI;", defaultUri, parts[0]); - assertEquals("Test 11: Incorrect local name;", "world", parts[1]); - assertEquals("Test 12: Incorrect raw name;", "world", parts[2]); - - assertNull("Test 13: Null expected for undeclared prefix.", - ns.processName("ck:lorem", parts, false)); - - assertNull("Test 14: Null expected for xmlns prefix.", - ns.processName("xmlns:ipsum", parts, false)); - - ns = new NamespaceSupport(); - ns.pushContext(); - assertNotNull("Test 15: Non-null value expected.", - ns.processName("world", parts, false)); - assertEquals("Test 16: Incorrect namespace URI;", "", parts[0]); - assertEquals("Test 17: Incorrect local name;", "world", parts[1]); - assertEquals("Test 18: Incorrect raw name;", "world", parts[2]); - } - - public void testProcessName_Attribute() { - String[] parts = new String[3]; - - assertNotNull("Test 1: Non-null value expected.", - ns.processName("ak:hello", parts, true)); - assertEquals("Test 2: Incorrect namespace URI;", marketUri, parts[0]); - assertEquals("Test 3: Incorrect local name;", "hello", parts[1]); - assertEquals("Test 4: Incorrect raw name;", "ak:hello", parts[2]); - - assertNotNull("Test 5: Non-null value expected.", - ns.processName("bk:", parts, true)); - assertEquals("Test 6: Incorrect namespace URI;", marketUri, parts[0]); - assertEquals("Test 7: Incorrect local name;", "", parts[1]); - assertEquals("Test 8: Incorrect raw name;", "bk:", parts[2]); - - assertNotNull("Test 9: Non-null value expected.", - ns.processName("world", parts, true)); - assertEquals("Test 10: Incorrect namespace URI;", "", parts[0]); - assertEquals("Test 11: Incorrect local name;", "world", parts[1]); - assertEquals("Test 12: Incorrect raw name;", "world", parts[2]); - - assertNull("Test 13: Null expected for undeclared prefix.", - ns.processName("ck:lorem", parts, true)); - - assertNull("Test 14: Null expected for xmlns prefix.", - ns.processName("xmlns:ipsum", parts, true)); - - ns = new NamespaceSupport(); - ns.setNamespaceDeclUris(true); - ns.pushContext(); - assertNotNull("Test 15: Non-null value expected.", - ns.processName("xmlns", parts, true)); - assertEquals("Test 16: Incorrect namespace URI;", NamespaceSupport.NSDECL, parts[0]); - assertEquals("Test 17: Incorrect local name;", "xmlns", parts[1]); - assertEquals("Test 18: Incorrect raw name;", "xmlns", parts[2]); - } - - @SuppressWarnings("unchecked") - private int countPrefixes() - { - ArrayList<String> prefixes = Collections.list(ns.getPrefixes()); - return prefixes.size(); - } -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/helpers/ParserAdapterTest.java b/luni/src/test/java/tests/api/org/xml/sax/helpers/ParserAdapterTest.java deleted file mode 100644 index 2344736..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/helpers/ParserAdapterTest.java +++ /dev/null @@ -1,335 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.helpers; - -import java.io.IOException; - -import junit.framework.TestCase; - -import org.xml.sax.AttributeList; -import org.xml.sax.Attributes; -import org.xml.sax.ContentHandler; -import org.xml.sax.DTDHandler; -import org.xml.sax.EntityResolver; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.Locator; -import org.xml.sax.Parser; -import org.xml.sax.SAXException; -import org.xml.sax.SAXNotRecognizedException; -import org.xml.sax.SAXNotSupportedException; -import org.xml.sax.helpers.AttributeListImpl; -import org.xml.sax.helpers.LocatorImpl; -import org.xml.sax.helpers.ParserAdapter; - -import tests.api.org.xml.sax.support.MethodLogger; -import tests.api.org.xml.sax.support.MockHandler; -import tests.api.org.xml.sax.support.MockParser; -import tests.api.org.xml.sax.support.MockResolver; - -@SuppressWarnings("deprecation") -public class ParserAdapterTest extends TestCase { - - // Note: In many cases we can only test that delegation works - // properly. The rest is outside the scope of the specification. - - private final static String FEATURES = "http://xml.org/sax/features/"; - - private final static String NAMESPACES = FEATURES + "namespaces"; - - private final static String NAMESPACE_PREFIXES = FEATURES - + "namespace-prefixes"; - - private final static String XMLNS_URIs = FEATURES + "xmlns-uris"; - - private MethodLogger logger = new MethodLogger(); - - private MockHandler handler = new MockHandler(logger); - - private Parser parser = new MockParser(logger); - - private ParserAdapter adapter = new ParserAdapter(parser); - - private void assertEquals(Object[] a, Object[] b) { - assertEquals(a.length, b.length); - - for (int i = 0; i < a.length; i++) { - assertEquals("Element #" + i + " must be equal", a[i], b[i]); - } - } - - @Override - public void setUp() { - adapter.setContentHandler(handler); - adapter.setDTDHandler(handler); - adapter.setErrorHandler(handler); - } - - @Override protected void tearDown() throws Exception { - super.tearDown(); - } - - public void testParserAdapter() { - System.setProperty("org.xml.sax.parser", - "tests.api.org.xml.sax.support.DoNothingParser"); - - try { - new ParserAdapter(); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testParserAdapterParser() { - // Ordinary case - @SuppressWarnings("unused") - ParserAdapter adapter = new ParserAdapter(parser); - - // Null case - try { - adapter = new ParserAdapter(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - // Expected - } - } - - public void testGetSetFeature() { - String[] features = new String[] { NAMESPACES, NAMESPACE_PREFIXES, - XMLNS_URIs }; - - for (String s: features) { - try { - adapter.setFeature(s, true); - assertEquals(true, adapter.getFeature(s)); - - adapter.setFeature(s, false); - assertEquals(false, adapter.getFeature(s)); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - try { - adapter.setFeature("http://argle.bargle", true); - fail("SAXNotRecognizedException expected"); - } catch (SAXNotRecognizedException e) { - // Expected - } catch (SAXNotSupportedException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testGetSetProperty() { - try { - adapter.setProperty("http://argle.bargle", ":)"); - fail("SAXNotRecognizedException expected"); - } catch (SAXNotRecognizedException e) { - // Expected - } catch (SAXNotSupportedException e) { - throw new RuntimeException("Unexpected exception", e); - } - - try { - adapter.getProperty("http://argle.bargle"); - fail("SAXNotRecognizedException expected"); - } catch (SAXNotRecognizedException e) { - // Expected - } catch (SAXNotSupportedException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testGetSetEntityResolver() { - EntityResolver resolver = new MockResolver(); - - adapter.setEntityResolver(resolver); - assertEquals(resolver, adapter.getEntityResolver()); - - adapter.setEntityResolver(null); - assertEquals(null, adapter.getEntityResolver()); - } - - public void testGetSetDTDHandler() { - adapter.setDTDHandler(null); - assertEquals(null, adapter.getDTDHandler()); - - adapter.setDTDHandler(handler); - assertEquals(handler, adapter.getDTDHandler()); - } - - public void testGetSetContentHandler() { - adapter.setContentHandler(null); - assertEquals(null, adapter.getContentHandler()); - - adapter.setContentHandler(handler); - assertEquals(handler, adapter.getContentHandler()); - } - - public void testGetSetErrorHandler() { - adapter.setErrorHandler(null); - assertEquals(null, adapter.getErrorHandler()); - - adapter.setErrorHandler(handler); - assertEquals(handler, adapter.getErrorHandler()); - } - - public void testParseString() { - try { - adapter.parse("foo"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } catch (IOException e) { - throw new RuntimeException("Unexpected exception", e); - } - - // The SAX RI creates an InputSource itself and then delegates to the - // "other" parse method. - assertEquals("parse", logger.getMethod()); - assertEquals(InputSource.class, logger.getArgs()[0].getClass()); - } - - public void testParseInputSource() { - InputSource source = new InputSource("foo"); - - try { - adapter.parse(source); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } catch (IOException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals("parse", logger.getMethod()); - assertEquals(new Object[] { source }, logger.getArgs()); - } - - public void testSetDocumentLocator() { - Locator l = new LocatorImpl(); - - adapter.setDocumentLocator(l); - - assertEquals(logger.size(), 1); - assertEquals("setDocumentLocator", logger.getMethod()); - assertEquals(new Object[] { l }, logger.getArgs()); - - adapter.setDocumentLocator(null); - - assertEquals(logger.size(), 2); - assertEquals("setDocumentLocator", logger.getMethod()); - assertEquals(new Object[] { null }, logger.getArgs()); - } - - public void testStartDocument() { - try { - adapter.startDocument(); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("startDocument", logger.getMethod()); - assertEquals(new Object[] {}, logger.getArgs()); - } - - public void testEndDocument() { - try { - adapter.endDocument(); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("endDocument", logger.getMethod()); - assertEquals(new Object[] {}, logger.getArgs()); - } - - public void testStartElement() { - AttributeListImpl atts = new AttributeListImpl(); - atts.addAttribute("john:doe", "int", "42"); - - try { - adapter.startDocument(); - adapter.startElement("foo:bar", atts); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals("startElement", logger.getMethod()); - assertEquals("", logger.getArgs()[0]); - assertEquals("", logger.getArgs()[1]); - assertEquals("foo:bar", logger.getArgs()[2]); - assertEquals("john:doe", ((Attributes)logger.getArgs()[3]).getQName(0)); - } - - public void testEndElement() { - AttributeListImpl atts = new AttributeListImpl(); - atts.addAttribute("john:doe", "int", "42"); - - try { - adapter.startDocument(); - adapter.startElement("foo:bar", atts); - adapter.endElement("foo:bar"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals("endElement", logger.getMethod()); - assertEquals(new String[] { "", "", "foo:bar" }, logger.getArgs()); - } - - public void testCharacters() { - char[] ch = "Android".toCharArray(); - - try { - adapter.characters(ch, 2, 5); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("characters", logger.getMethod()); - assertEquals(new Object[] { ch, 2, 5 }, logger.getArgs()); - } - - public void testIgnorableWhitespace() { - char[] ch = " ".toCharArray(); - - try { - adapter.ignorableWhitespace(ch, 0, 5); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("ignorableWhitespace", logger.getMethod()); - assertEquals(new Object[] { ch, 0, 5 }, logger.getArgs()); - } - - public void testProcessingInstruction() { - try { - adapter.processingInstruction("foo", "bar"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("processingInstruction", logger.getMethod()); - assertEquals(new Object[] { "foo" , "bar" }, logger.getArgs()); - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/helpers/ParserFactoryTest.java b/luni/src/test/java/tests/api/org/xml/sax/helpers/ParserFactoryTest.java deleted file mode 100644 index b59ce50..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/helpers/ParserFactoryTest.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.helpers; - -import junit.framework.TestCase; - -import org.xml.sax.helpers.ParserFactory; - -@SuppressWarnings("deprecation") -public class ParserFactoryTest extends TestCase { - - @Override protected void tearDown() throws Exception { - super.tearDown(); - } - - public void testMakeParser() throws ClassNotFoundException, - IllegalAccessException, InstantiationException { - - System.clearProperty("org.xml.sax.parser"); - - // Property not set at all - try { - ParserFactory.makeParser(); - fail("expected NullPointerException was not thrown"); - } catch (NullPointerException e) { - // Expected - } - - // Unknown class - System.setProperty("org.xml.sax.parser", "foo.bar.SAXParser"); - - try { - ParserFactory.makeParser(); - fail("expected ClassNotFoundException was not thrown"); - } catch (ClassNotFoundException e) { - // Expected - } - - // Non-accessible class - System.setProperty("org.xml.sax.parser", - "tests.api.org.xml.sax.support.NoAccessParser"); - - try { - ParserFactory.makeParser(); - fail("expected IllegalAccessException was not thrown"); - } catch (IllegalAccessException e) { - // Expected - } - - // Non-instantiable class - System.setProperty("org.xml.sax.parser", - "tests.api.org.xml.sax.support.NoInstanceParser"); - - try { - ParserFactory.makeParser(); - fail("expected InstantiationException was not thrown"); - } catch (InstantiationException e) { - // Expected - } - - // Non-Parser class - System.setProperty("org.xml.sax.parser", - "tests.api.org.xml.sax.support.NoSubclassParser"); - - try { - ParserFactory.makeParser(); - fail("expected ClassCastException was not thrown"); - } catch (ClassCastException e) { - // Expected - } - - // Good one, finally - System.setProperty("org.xml.sax.parser", - "tests.api.org.xml.sax.support.DoNothingParser"); - - ParserFactory.makeParser(); - - } - - public void testMakeParserString() throws ClassNotFoundException, - IllegalAccessException, InstantiationException { - // No class - try { - ParserFactory.makeParser(null); - fail("expected NullPointerException was not thrown"); - } catch (NullPointerException e) { - // Expected - } - - // Unknown class - try { - ParserFactory.makeParser("foo.bar.SAXParser"); - fail("expected ClassNotFoundException was not thrown"); - } catch (ClassNotFoundException e) { - // Expected - } - - // Non-accessible class - try { - ParserFactory.makeParser( - "tests.api.org.xml.sax.support.NoAccessParser"); - fail("expected IllegalAccessException was not thrown"); - } catch (IllegalAccessException e) { - // Expected - } - - // Non-instantiable class - try { - ParserFactory.makeParser( - "tests.api.org.xml.sax.support.NoInstanceParser"); - fail("expected InstantiationException was not thrown"); - } catch (InstantiationException e) { - // Expected - } - - // Non-Parser class - try { - ParserFactory.makeParser( - "tests.api.org.xml.sax.support.NoSubclassParser"); - fail("expected ClassCastException was not thrown"); - } catch (ClassCastException e) { - // Expected - } - - // Good one, finally - ParserFactory.makeParser( - "tests.api.org.xml.sax.support.DoNothingParser"); - - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/helpers/XMLFilterImplTest.java b/luni/src/test/java/tests/api/org/xml/sax/helpers/XMLFilterImplTest.java deleted file mode 100644 index d00879b..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/helpers/XMLFilterImplTest.java +++ /dev/null @@ -1,484 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.helpers; - -import java.io.IOException; - -import junit.framework.TestCase; - -import org.xml.sax.Attributes; -import org.xml.sax.ContentHandler; -import org.xml.sax.DTDHandler; -import org.xml.sax.EntityResolver; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.Locator; -import org.xml.sax.SAXException; -import org.xml.sax.SAXNotRecognizedException; -import org.xml.sax.SAXNotSupportedException; -import org.xml.sax.SAXParseException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.AttributesImpl; -import org.xml.sax.helpers.LocatorImpl; -import org.xml.sax.helpers.XMLFilterImpl; - -import tests.api.org.xml.sax.support.MethodLogger; -import tests.api.org.xml.sax.support.MockFilter; -import tests.api.org.xml.sax.support.MockHandler; -import tests.api.org.xml.sax.support.MockResolver; - -public class XMLFilterImplTest extends TestCase { - - // Note: In many cases we can only test that delegation works - // properly. The rest is outside the scope of the specification. - - private MethodLogger logger = new MethodLogger(); - - private MockHandler handler = new MockHandler(logger); - - private XMLFilterImpl parent = new MockFilter(logger); - - private XMLFilterImpl child = new XMLFilterImpl(parent); - - private XMLFilterImpl orphan = new XMLFilterImpl(); - - private void assertEquals(Object[] a, Object[] b) { - assertEquals(a.length, b.length); - - for (int i = 0; i < a.length; i++) { - assertEquals("Element #" + i + " must be equal", a[i], b[i]); - } - } - - public void setUp() { - parent.setContentHandler(handler); - parent.setDTDHandler(handler); - parent.setErrorHandler(handler); - - child.setContentHandler(handler); - child.setDTDHandler(handler); - child.setErrorHandler(handler); - } - - public void testXMLFilterImpl() { - assertEquals(null, parent.getParent()); - } - - public void testXMLFilterImplXMLReader() { - // Ordinary case - assertEquals(null, parent.getParent()); - - // null case - XMLFilterImpl filter = new XMLFilterImpl(null); - assertEquals(null, filter.getParent()); - } - - public void testGetSetParent() { - child.setParent(null); - assertEquals(null, child.getParent()); - - child.setParent(parent); - assertEquals(parent, child.getParent()); - } - - public void testGetSetFeature() { - // Ordinary case - try { - child.setFeature("foo", true); - assertEquals(true, child.getFeature("foo")); - - child.setFeature("foo", false); - assertEquals(false, child.getFeature("foo")); - } catch (SAXNotRecognizedException e) { - throw new RuntimeException("Unexpected exception", e); - } catch (SAXNotSupportedException e) { - throw new RuntimeException("Unexpected exception", e); - } - - // No parent case - try { - orphan.setFeature("foo", false); - fail("SAXNotRecognizedException expected"); - } catch (SAXNotRecognizedException e) { - // Expected - } catch (SAXNotSupportedException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testGetSetProperty() { - // Ordinary case - try { - child.setProperty("foo", "bar"); - assertEquals("bar", child.getProperty("foo")); - - child.setProperty("foo", null); - assertEquals(null, child.getProperty("foo")); - } catch (SAXNotRecognizedException e) { - throw new RuntimeException("Unexpected exception", e); - } catch (SAXNotSupportedException e) { - throw new RuntimeException("Unexpected exception", e); - } - - // No parent case - try { - orphan.setProperty("foo", "bar"); - fail("SAXNotRecognizedException expected"); - } catch (SAXNotRecognizedException e) { - // Expected - } catch (SAXNotSupportedException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testGetSetEntityResolver() { - EntityResolver resolver = new MockResolver(); - - parent.setEntityResolver(resolver); - assertEquals(resolver, parent.getEntityResolver()); - - parent.setEntityResolver(null); - assertEquals(null, parent.getEntityResolver()); - } - - public void testGetSetDTDHandler() { - parent.setDTDHandler(null); - assertEquals(null, parent.getDTDHandler()); - - parent.setDTDHandler(handler); - assertEquals(handler, parent.getDTDHandler()); - } - - public void testGetSetContentHandler() { - parent.setContentHandler(null); - assertEquals(null, parent.getContentHandler()); - - parent.setContentHandler(handler); - assertEquals(handler, parent.getContentHandler()); - } - - public void testGetSetErrorHandler() { - parent.setErrorHandler(null); - assertEquals(null, parent.getErrorHandler()); - - parent.setErrorHandler(handler); - assertEquals(handler, parent.getErrorHandler()); - } - - public void testParseInputSource() { - InputSource is = new InputSource(); - - // Ordinary case - try { - child.parse(is); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } catch (IOException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(1, logger.size()); - assertEquals("parse", logger.getMethod()); - - // No parent case - try { - orphan.parse(is); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - // Expected - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } catch (IOException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testParseString() { - // Ordinary case - try { - child.parse("foo"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } catch (IOException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(1, logger.size()); - assertEquals("parse", logger.getMethod()); - - // No parent case - try { - orphan.parse("foo"); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - // Expected - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } catch (IOException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testResolveEntity() { - InputSource expected = new InputSource(); - - MockResolver resolver = new MockResolver(); - resolver.addEntity("foo", "bar", expected); - - InputSource result = null; - - parent.setEntityResolver(resolver); - - // Ordinary case - try { - result = parent.resolveEntity("foo", "bar"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } catch (IOException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(expected, result); - - // No entity resolver case - parent.setEntityResolver(null); - - try { - result = parent.resolveEntity("foo", "bar"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } catch (IOException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(null, result); - } - - public void testNotationDecl() { - try { - parent.notationDecl("foo", "bar", "foobar"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("notationDecl", logger.getMethod()); - assertEquals(new Object[] { "foo", "bar", "foobar" }, - logger.getArgs()); - } - - public void testUnparsedEntityDecl() { - try { - parent.unparsedEntityDecl("foo", "bar", "gabba", "hey"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("unparsedEntityDecl", logger.getMethod()); - assertEquals(new Object[] { "foo", "bar", "gabba", "hey" }, - logger.getArgs()); - } - - public void testSetDocumentLocator() { - Locator l = new LocatorImpl(); - - child.setDocumentLocator(l); - - assertEquals(logger.size(), 1); - assertEquals("setDocumentLocator", logger.getMethod()); - assertEquals(new Object[] { l }, logger.getArgs()); - - child.setDocumentLocator(null); - - assertEquals(logger.size(), 2); - assertEquals("setDocumentLocator", logger.getMethod()); - assertEquals(new Object[] { null }, logger.getArgs()); - } - - public void testStartDocument() { - try { - parent.startDocument(); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("startDocument", logger.getMethod()); - assertEquals(new Object[] {}, logger.getArgs()); - } - - public void testEndDocument() { - try { - parent.endDocument(); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("endDocument", logger.getMethod()); - assertEquals(new Object[] {}, logger.getArgs()); - } - - public void testStartPrefixMapping() { - try { - parent.startPrefixMapping("foo", "http://some.uri"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("startPrefixMapping", logger.getMethod()); - assertEquals(new Object[] { "foo", "http://some.uri" }, - logger.getArgs()); - } - - public void testEndPrefixMapping() { - try { - parent.endPrefixMapping("foo"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("endPrefixMapping", logger.getMethod()); - assertEquals(new Object[] { "foo" }, logger.getArgs()); - } - - public void testStartElement() { - Attributes atts = new AttributesImpl(); - - try { - parent.startElement("http://some.uri", "bar", "foo:bar", atts); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("startElement", logger.getMethod()); - assertEquals(new Object[] { "http://some.uri", "bar", "foo:bar", atts }, - logger.getArgs()); - } - - public void testEndElement() { - try { - parent.endElement("http://some.uri", "bar", "foo:bar"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("endElement", logger.getMethod()); - assertEquals(new Object[] { "http://some.uri", "bar", "foo:bar" }, - logger.getArgs()); - } - - public void testCharacters() { - char[] ch = "Android".toCharArray(); - - try { - parent.characters(ch, 2, 5); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("characters", logger.getMethod()); - assertEquals(new Object[] { ch, 2, 5 }, logger.getArgs()); - } - - public void testIgnorableWhitespace() { - char[] ch = " ".toCharArray(); - - try { - parent.ignorableWhitespace(ch, 0, 5); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("ignorableWhitespace", logger.getMethod()); - assertEquals(new Object[] { ch, 0, 5 }, logger.getArgs()); - } - - public void testProcessingInstruction() { - try { - parent.processingInstruction("foo", "bar"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("processingInstruction", logger.getMethod()); - assertEquals(new Object[] { "foo", "bar" }, logger.getArgs()); - } - - public void testSkippedEntity() { - try { - parent.skippedEntity("foo"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("skippedEntity", logger.getMethod()); - assertEquals(new Object[] { "foo" }, logger.getArgs()); - } - - public void testWarning() { - SAXParseException exception = new SAXParseException("Oops!", null); - - try { - parent.warning(exception); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("warning", logger.getMethod()); - assertEquals(new Object[] { exception }, logger.getArgs()); - } - - public void testError() { - SAXParseException exception = new SAXParseException("Oops!", null); - - try { - parent.error(exception); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("error", logger.getMethod()); - assertEquals(new Object[] { exception }, logger.getArgs()); - } - - public void testFatalError() { - SAXParseException exception = new SAXParseException("Oops!", null); - - try { - parent.fatalError(exception); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("fatalError", logger.getMethod()); - assertEquals(new Object[] { exception }, logger.getArgs()); - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/helpers/XMLReaderAdapterTest.java b/luni/src/test/java/tests/api/org/xml/sax/helpers/XMLReaderAdapterTest.java deleted file mode 100644 index 16104b3..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/helpers/XMLReaderAdapterTest.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.helpers; - -import java.io.IOException; -import java.util.Locale; - -import junit.framework.TestCase; - -import org.xml.sax.AttributeList; -import org.xml.sax.Attributes; -import org.xml.sax.DTDHandler; -import org.xml.sax.DocumentHandler; -import org.xml.sax.EntityResolver; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.Locator; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.AttributesImpl; -import org.xml.sax.helpers.LocatorImpl; -import org.xml.sax.helpers.XMLReaderAdapter; - -import tests.api.org.xml.sax.support.MethodLogger; -import tests.api.org.xml.sax.support.MockHandler; -import tests.api.org.xml.sax.support.MockReader; -import tests.api.org.xml.sax.support.MockResolver; - -@SuppressWarnings("deprecation") -public class XMLReaderAdapterTest extends TestCase { - - // Note: In many cases we can only test that delegation works - // properly. The rest is outside the scope of the specification. - - private MethodLogger logger = new MethodLogger(); - - private MockHandler handler = new MockHandler(logger); - - private XMLReader reader = new MockReader(logger); - - private XMLReaderAdapter adapter = new XMLReaderAdapter(reader); - - private void assertEquals(Object[] a, Object[] b) { - assertEquals(a.length, b.length); - - for (int i = 0; i < a.length; i++) { - assertEquals("Element #" + i + " must be equal", a[i], b[i]); - } - } - - @Override - public void setUp() { - adapter.setDocumentHandler(handler); - adapter.setDTDHandler(handler); - adapter.setErrorHandler(handler); - } - - @Override protected void tearDown() throws Exception { - super.tearDown(); - } - - public void testXMLReaderAdapter() { - System.setProperty("org.xml.sax.driver", - "tests.api.org.xml.sax.support.DoNothingXMLReader"); - - try { - new XMLReaderAdapter(); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - } - - public void testXMLReaderAdapterXMLReader() { - // Ordinary case - @SuppressWarnings("unused") - XMLReaderAdapter adapter = new XMLReaderAdapter(reader); - - // Null case - try { - adapter = new XMLReaderAdapter(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - // Expected - } - } - - public void testSetLocale() { - // SAX RI does not support this, hence always expect exception - try { - adapter.setLocale(Locale.getDefault()); - fail("SAXException expected"); - } catch (SAXException e) { - // Expected - } - } - - public void testSetEntityResolver() { - EntityResolver resolver = new MockResolver(); - - // Ordinary case - adapter.setEntityResolver(resolver); - assertEquals(resolver, reader.getEntityResolver()); - - // null case - adapter.setEntityResolver(null); - assertEquals(null, reader.getEntityResolver()); - } - - public void testSetDTDHandler() { - // Ordinary case - assertEquals(handler, reader.getDTDHandler()); - - // null case - adapter.setDTDHandler(null); - assertEquals(null, reader.getDTDHandler()); - } - - public void testSetDocumentHandler() { - // There is no getter for the DocumentHandler, so we can only test - // indirectly whether is has been set correctly. - try { - adapter.startDocument(); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals("startDocument", logger.getMethod()); - assertEquals(new Object[] { }, logger.getArgs()); - - // null case - adapter.setDocumentHandler(null); - } - - public void testSetErrorHandler() { - // Ordinary case - assertEquals(handler, reader.getErrorHandler()); - - // null case - adapter.setErrorHandler(null); - assertEquals(null, reader.getErrorHandler()); - } - - public void testParseString() { - try { - adapter.parse("foo"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } catch (IOException e) { - throw new RuntimeException("Unexpected exception", e); - } - - // The SAX RI creates an InputSource itself and then delegates to the - // "other" parse method. - assertEquals("parse", logger.getMethod(0)); - assertEquals(InputSource.class, logger.getArgs(0)[0].getClass()); - } - - public void testParseInputSource() { - InputSource source = new InputSource("foo"); - - try { - adapter.parse(source); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } catch (IOException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals("parse", logger.getMethod()); - assertEquals(new Object[] { source }, logger.getArgs()); - } - - public void testSetDocumentLocator() { - // Ordinary case - LocatorImpl locator = new LocatorImpl(); - adapter.setDocumentLocator(locator); - - assertEquals("setDocumentLocator", logger.getMethod()); - assertEquals(new Object[] { locator }, logger.getArgs()); - - // null case (for the DocumentHandler itself!) - adapter.setDocumentHandler(null); - adapter.setDocumentLocator(locator); - } - - public void testStartDocument() { - try { - adapter.startDocument(); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("startDocument", logger.getMethod()); - assertEquals(new Object[] {}, logger.getArgs()); - } - - public void testEndDocument() { - try { - adapter.endDocument(); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("endDocument", logger.getMethod()); - assertEquals(new Object[] {}, logger.getArgs()); - } - - public void testStartPrefixMapping() { - adapter.startPrefixMapping("foo", "http://some.uri"); - assertEquals(logger.size(), 0); - } - - public void testEndPrefixMapping() { - adapter.endPrefixMapping("foo"); - assertEquals(logger.size(), 0); - } - - public void testStartElement() { - AttributesImpl atts = new AttributesImpl(); - atts.addAttribute("http://some.other.uri", "gabba", "gabba:hey", - "int", "42"); - - try { - adapter.startElement("http://some.uri", "bar", "foo:bar", atts); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("startElement", logger.getMethod()); - assertEquals("foo:bar", logger.getArgs()[0]); - assertEquals("gabba:hey", - ((AttributeList)logger.getArgs()[1]).getName(0)); - } - - public void testEndElement() { - try { - adapter.endElement("http://some.uri", "bar", "foo:bar"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("endElement", logger.getMethod()); - assertEquals(new Object[] { "foo:bar" }, logger.getArgs()); - } - - public void testCharacters() { - char[] ch = "Android".toCharArray(); - - try { - adapter.characters(ch, 2, 5); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("characters", logger.getMethod()); - assertEquals(new Object[] { ch, 2, 5 }, logger.getArgs()); - } - - public void testIgnorableWhitespace() { - char[] ch = " ".toCharArray(); - - try { - adapter.ignorableWhitespace(ch, 0, 5); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("ignorableWhitespace", logger.getMethod()); - assertEquals(new Object[] { ch, 0, 5 }, logger.getArgs()); - } - - public void testProcessingInstruction() { - try { - adapter.processingInstruction("foo", "bar"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 1); - assertEquals("processingInstruction", logger.getMethod()); - assertEquals(new Object[] { "foo" , "bar" }, logger.getArgs()); - } - - public void testSkippedEntity() { - try { - adapter.skippedEntity("foo"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - assertEquals(logger.size(), 0); - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/helpers/XMLReaderFactoryTest.java b/luni/src/test/java/tests/api/org/xml/sax/helpers/XMLReaderFactoryTest.java deleted file mode 100644 index 8205dfd..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/helpers/XMLReaderFactoryTest.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.helpers; - -import junit.framework.TestCase; - -import org.xml.sax.SAXException; -import org.xml.sax.helpers.XMLReaderFactory; - -public class XMLReaderFactoryTest extends TestCase { - - @Override protected void setUp() throws Exception { - super.setUp(); - } - - @Override protected void tearDown() throws Exception { - super.tearDown(); - } - - public void testCreateXMLReader() { - // Property not set at all - try { - XMLReaderFactory.createXMLReader(); - } catch (SAXException e) { - // Expected - } - - // Unknown class - System.setProperty("org.xml.sax.driver", "foo.bar.XMLReader"); - - try { - XMLReaderFactory.createXMLReader(); - } catch (SAXException e) { - // Expected - } - - // Non-accessible class - System.setProperty("org.xml.sax.driver", - "tests.api.org.xml.sax.support.NoAccessXMLReader"); - - try { - XMLReaderFactory.createXMLReader(); - } catch (SAXException e) { - // Expected - } - - // Non-instantiable class - System.setProperty("org.xml.sax.driver", - "tests.api.org.xml.sax.support.NoInstanceXMLReader"); - - try { - XMLReaderFactory.createXMLReader(); - } catch (SAXException e) { - // Expected - } - - // Non-XMLReader class - System.setProperty("org.xml.sax.driver", - "tests.api.org.xml.sax.support.NoSubclassXMLReader"); - - try { - XMLReaderFactory.createXMLReader(); - } catch (ClassCastException e) { - // Expected - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - // Good one, finally - System.setProperty("org.xml.sax.driver", - "tests.api.org.xml.sax.support.DoNothingXMLReader"); - - try { - XMLReaderFactory.createXMLReader(); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - } - - public void testMakeParserString() { - // No class - try { - XMLReaderFactory.createXMLReader(null); - } catch (NullPointerException e) { - // Expected - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - // Unknown class - try { - XMLReaderFactory.createXMLReader("foo.bar.XMLReader"); - } catch (SAXException e) { - // Expected - } - - // Non-accessible class - try { - XMLReaderFactory.createXMLReader( - "tests.api.org.xml.sax.support.NoAccessXMLReader"); - } catch (SAXException e) { - // Expected - } - - // Non-instantiable class - try { - XMLReaderFactory.createXMLReader( - "tests.api.org.xml.sax.support.NoInstanceXMLReader"); - } catch (SAXException e) { - // Expected - } - - // Non-Parser class - try { - XMLReaderFactory.createXMLReader( - "tests.api.org.xml.sax.support.NoSubclassXMLReader"); - } catch (SAXException e) { - // Expected - } - - // Good one, finally - try { - XMLReaderFactory.createXMLReader( - "tests.api.org.xml.sax.support.DoNothingXMLReader"); - } catch (SAXException e) { - throw new RuntimeException("Unexpected exception", e); - } - - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/BrokenInputStream.java b/luni/src/test/java/tests/api/org/xml/sax/support/BrokenInputStream.java deleted file mode 100644 index 8136b86..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/support/BrokenInputStream.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.support; - -import java.io.IOException; -import java.io.InputStream; - -/** - * Implements an InputStream what wraps another InputStream and throws an - * IOException after having read a specified number of bytes. Used for - * injecting IOExceptions on lower levels. - */ -public class BrokenInputStream extends InputStream { - - private InputStream stream; - - private int offset; - - public BrokenInputStream(InputStream stream, int offset) { - super(); - - this.stream = stream; - this.offset = offset; - } - - @Override - public int read() throws IOException { - if (offset == 0) { - throw new IOException("Injected exception"); - } - - offset--; - return stream.read(); - } - - @Override - public void close() throws IOException { - stream.close(); - } -}
\ No newline at end of file diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/DoNothingParser.java b/luni/src/test/java/tests/api/org/xml/sax/support/DoNothingParser.java deleted file mode 100644 index c18b6ee..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/support/DoNothingParser.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.support; - -import org.xml.sax.DTDHandler; -import org.xml.sax.DocumentHandler; -import org.xml.sax.EntityResolver; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.Parser; - -import java.util.Locale; - -/** - * A SAX Parser that does nothing, but can be instantiated properly. - */ -@SuppressWarnings("deprecation") -public class DoNothingParser implements Parser { - - public void parse(InputSource source) { - } - - public void parse(String systemId) { - } - - public void setDocumentHandler(DocumentHandler handler) { - } - - public void setDTDHandler(DTDHandler handler) { - } - - public void setEntityResolver(EntityResolver resolver) { - } - - public void setErrorHandler(ErrorHandler handler) { - } - - public void setLocale(Locale locale) { - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/DoNothingXMLReader.java b/luni/src/test/java/tests/api/org/xml/sax/support/DoNothingXMLReader.java deleted file mode 100644 index 8687bff..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/support/DoNothingXMLReader.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.support; - -import org.xml.sax.ContentHandler; -import org.xml.sax.DTDHandler; -import org.xml.sax.EntityResolver; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.XMLReader; - -/** - * An XMLReader that does nothing, but can be instantiated properly. - */ -public class DoNothingXMLReader implements XMLReader { - - public ContentHandler getContentHandler() { - return null; - } - - public DTDHandler getDTDHandler() { - return null; - } - - public EntityResolver getEntityResolver() { - return null; - } - - public ErrorHandler getErrorHandler() { - return null; - } - - public boolean getFeature(String name) { - return false; - } - - public Object getProperty(String name) { - return null; - } - - public void parse(InputSource input) { - } - - public void parse(String systemId) { - } - - public void setContentHandler(ContentHandler handler) { - } - - public void setDTDHandler(DTDHandler handler) { - } - - public void setEntityResolver(EntityResolver resolver) { - } - - public void setErrorHandler(ErrorHandler handler) { - } - - public void setFeature(String name, boolean value) { - } - - public void setProperty(String name, Object value) { - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/MethodLogger.java b/luni/src/test/java/tests/api/org/xml/sax/support/MethodLogger.java deleted file mode 100644 index ad8ef5f..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/support/MethodLogger.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.support; - -import java.util.ArrayList; -import java.util.List; - -/** - * A simple helper class that logs method calls by storing method names and - * parameter lists. Used as a foundation for various simple SAX handlers. - */ -public class MethodLogger { - - /** - * The names of the invoked methods, in order. - */ - private List<String> methods = new ArrayList<String>(); - - /** - * The parameter lists of the invoked methods, in order. - */ - private List<Object[]> argLists = new ArrayList<Object[]>(); - - /** - * Adds a method call with a variable list of arguments. - */ - public void add(String method, Object ... args) { - Object[] argsCopy = new Object[args.length]; - System.arraycopy(args, 0, argsCopy, 0, args.length); - - methods.add(method); - argLists.add(argsCopy); - } - - /** - * Returns the number of method invoked so far. - */ - public int size() { - return methods.size(); - } - - /** - * Returns the method name stored at the given index. - */ - public String getMethod(int index) { - return methods.get(index); - } - - /** - * Returns the name of the last method that was invoked. Returns null if no - * method calls have been logged so far. - */ - public String getMethod() { - return (size() == 0 ? null : getMethod(size() - 1)); - } - - /** - * Returns the argument array stored at the given index. May be empty, but - * not null. - */ - public Object[] getArgs(int index) { - return argLists.get(index); - } - - /** - * Returns the argument array of the last method that was invoked. Returns - * null if no method has been invoked so far. - */ - public Object[] getArgs() { - return (size() == 0 ? null : getArgs(size() - 1)); - } - - /** - * Clears the log. - */ - public void clear() { - methods.clear(); - argLists.clear(); - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/MockFilter.java b/luni/src/test/java/tests/api/org/xml/sax/support/MockFilter.java deleted file mode 100644 index 1189ebd..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/support/MockFilter.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.support; - -import java.io.IOException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.SAXNotRecognizedException; -import org.xml.sax.SAXNotSupportedException; -import org.xml.sax.helpers.XMLFilterImpl; - -/** - * A helper class that extends XMLFilterImpl, provides dummy feature/property - * management, and logs some method calls. - */ -public class MockFilter extends XMLFilterImpl { - - private MethodLogger logger; - - private Set<String> features = new HashSet<String>(); - - private Map<String, Object> properties = new HashMap<String, Object>(); - - public MockFilter(MethodLogger logger) { - super(); - this.logger = logger; - } - - @Override - public boolean getFeature(String name) throws SAXNotRecognizedException, - SAXNotSupportedException { - return features.contains(name); - } - - @Override - public Object getProperty(String name) throws SAXNotRecognizedException, - SAXNotSupportedException { - return properties.get(name); - } - - @Override - public void setFeature(String name, boolean value) { - if (value) { - features.add(name); - } else { - features.remove(name); - } - } - - @Override - public void setProperty(String name, Object value) throws SAXNotRecognizedException, - SAXNotSupportedException { - if (value == null) { - properties.remove(name); - } else { - properties.put(name, value); - } - } - - @Override - public void parse(InputSource input) throws SAXException, IOException { - logger.add("parse", input); - } - - @Override - public void parse(String systemId) throws SAXException, IOException { - logger.add("parse", systemId); - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/MockHandler.java b/luni/src/test/java/tests/api/org/xml/sax/support/MockHandler.java deleted file mode 100644 index 55757c9..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/support/MockHandler.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.support; - -import org.xml.sax.AttributeList; -import org.xml.sax.Attributes; -import org.xml.sax.ContentHandler; -import org.xml.sax.DTDHandler; -import org.xml.sax.DocumentHandler; -import org.xml.sax.ErrorHandler; -import org.xml.sax.Locator; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; -import org.xml.sax.ext.LexicalHandler; - -/** - * A helper class that implements the various SAX callback interfaces and logs - * method calls. - */ -@SuppressWarnings("deprecation") -public class MockHandler implements ContentHandler, DTDHandler, DocumentHandler, - ErrorHandler, LexicalHandler { - - private MethodLogger logger; - - public MockHandler(MethodLogger logger) { - super(); - this.logger = logger; - } - - public void characters(char[] ch, int start, int length) throws SAXException { - logger.add("characters", ch, start, length); - } - - public void endDocument() throws SAXException { - logger.add("endDocument"); - } - - public void endElement(String name) throws SAXException { - logger.add("endElement", name); - } - - public void endElement(String uri, String localName, String name) throws SAXException { - logger.add("endElement", uri, localName, name); - } - - public void endPrefixMapping(String prefix) throws SAXException { - logger.add("endPrefixMapping", prefix); - } - - public void error(SAXParseException exception) throws SAXException { - logger.add("error", exception); - } - - public void fatalError(SAXParseException exception) throws SAXException { - logger.add("fatalError", exception); - } - - public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { - logger.add("ignorableWhitespace", ch, start, length); - } - - public void notationDecl(String name, String publicId, String systemId) throws SAXException { - logger.add("notationDecl", name, publicId, systemId); - } - - public void processingInstruction(String target, String data) throws SAXException { - logger.add("processingInstruction", target, data); - } - - public void setDocumentLocator(Locator locator) { - logger.add("setDocumentLocator", locator); - } - - public void skippedEntity(String name) throws SAXException { - logger.add("skippedEntity", name); - } - - public void startDocument() throws SAXException { - logger.add("startDocument"); - } - - public void startElement(String name, AttributeList atts) throws SAXException { - logger.add("startElement", name, atts); - } - - public void startElement(String uri, String localName, String name, Attributes atts) - throws SAXException { - logger.add("startElement", uri, localName, name, atts); - } - - public void startPrefixMapping(String prefix, String uri) throws SAXException { - logger.add("startPrefixMapping", prefix, uri); - } - - public void unparsedEntityDecl(String name, String publicId, String systemId, - String notationName) throws SAXException { - logger.add("unparsedEntityDecl", name, publicId, systemId, notationName); - } - - public void warning(SAXParseException exception) throws SAXException { - logger.add("warning", exception); - } - - public void comment(char[] ch, int start, int length) throws SAXException { - logger.add("comment", ch, start, length); - } - - public void endCDATA() throws SAXException { - logger.add("endCDATA"); - } - - public void endDTD() throws SAXException { - logger.add("endDTD"); - } - - public void endEntity(String name) throws SAXException { - logger.add("endEntity", name); - } - - public void startCDATA() throws SAXException { - logger.add("startCDATA"); - } - - public void startDTD(String name, String publicId, String systemId) throws SAXException { - logger.add("startDTD", name, publicId, systemId); - } - - public void startEntity(String name) throws SAXException { - logger.add("startEntity", name); - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/MockParser.java b/luni/src/test/java/tests/api/org/xml/sax/support/MockParser.java deleted file mode 100644 index e19e14e..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/support/MockParser.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.support; - -import java.io.IOException; -import java.util.Locale; - -import org.xml.sax.DTDHandler; -import org.xml.sax.DocumentHandler; -import org.xml.sax.EntityResolver; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.Parser; -import org.xml.sax.SAXException; - -@SuppressWarnings("deprecation") -public class MockParser implements Parser { - - private MethodLogger logger; - - public MockParser(MethodLogger logger) { - super(); - this.logger = logger; - } - - public void parse(InputSource source) throws SAXException, IOException { - logger.add("parse", source); - } - - public void parse(String systemId) throws SAXException, IOException { - logger.add("parse", systemId); - } - - public void setDTDHandler(DTDHandler handler) { - logger.add("setDTDHandler", handler); - } - - public void setDocumentHandler(DocumentHandler handler) { - logger.add("setDocumentHandler", handler); - } - - public void setEntityResolver(EntityResolver resolver) { - logger.add("setEntityResolver", resolver); - } - - public void setErrorHandler(ErrorHandler handler) { - logger.add("setErrorHandler", handler); - } - - public void setLocale(Locale locale) throws SAXException { - logger.add("setLocale", locale); - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/MockReader.java b/luni/src/test/java/tests/api/org/xml/sax/support/MockReader.java deleted file mode 100644 index 2f0081c..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/support/MockReader.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.support; - -import java.io.IOException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.xml.sax.ContentHandler; -import org.xml.sax.DTDHandler; -import org.xml.sax.EntityResolver; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.SAXNotRecognizedException; -import org.xml.sax.SAXNotSupportedException; -import org.xml.sax.XMLReader; - -/** - * A helper class that implements the SAX XMLReader interface and logs method - * calls. - */ -public class MockReader implements XMLReader { - - private MethodLogger logger; - - private ContentHandler contentHandler; - - private DTDHandler dtdHandler; - - private EntityResolver resolver; - - private ErrorHandler errorHandler; - - private Set<String> features = new HashSet<String>(); - - private Map<String, Object> properties = new HashMap<String, Object>(); - - public MockReader(MethodLogger logger) { - super(); - this.logger = logger; - } - - - public ContentHandler getContentHandler() { - return contentHandler; - } - - public DTDHandler getDTDHandler() { - return dtdHandler; - } - - public EntityResolver getEntityResolver() { - return resolver; - } - - public ErrorHandler getErrorHandler() { - return errorHandler; - } - - public boolean getFeature(String name) throws SAXNotRecognizedException, - SAXNotSupportedException { - return features.contains(name); - } - - public Object getProperty(String name) throws SAXNotRecognizedException, - SAXNotSupportedException { - return properties.get(name); - } - - public void parse(InputSource input) throws IOException, SAXException { - logger.add("parse", input); - } - - public void parse(String systemId) throws IOException, SAXException { - logger.add("parse", systemId); - } - - public void setContentHandler(ContentHandler handler) { - this.contentHandler = handler; - } - - public void setDTDHandler(DTDHandler handler) { - this.dtdHandler = handler; - } - - public void setEntityResolver(EntityResolver resolver) { - this.resolver = resolver; - } - - public void setErrorHandler(ErrorHandler handler) { - this.errorHandler = handler; - } - - public void setFeature(String name, boolean value) { - if (value) { - features.add(name); - } else { - features.remove(name); - } - } - - public void setProperty(String name, Object value) throws SAXNotRecognizedException, - SAXNotSupportedException { - if (value == null) { - properties.remove(name); - } else { - properties.put(name, value); - } - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/MockResolver.java b/luni/src/test/java/tests/api/org/xml/sax/support/MockResolver.java deleted file mode 100644 index df4ddbf..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/support/MockResolver.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.support; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.xml.sax.EntityResolver; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -/** - * A helper class for resolving entities. - */ -public class MockResolver implements EntityResolver { - - private Map<String, InputSource> entities = new HashMap<String, InputSource>(); - - public void addEntity(String publicId, String systemId, InputSource source) { - entities.put("[" + publicId + ":" + systemId + "]", source); - } - - public void removeEntity(String publicId, String systemId) { - entities.remove("[" + publicId + ":" + systemId + "]"); - } - - public InputSource resolveEntity(String publicId, String systemId) - throws SAXException, IOException { - return entities.get("[" + publicId + ":" + systemId + "]"); - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/NoAccessParser.java b/luni/src/test/java/tests/api/org/xml/sax/support/NoAccessParser.java deleted file mode 100644 index 9fca514..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/support/NoAccessParser.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.support; - -import org.xml.sax.DTDHandler; -import org.xml.sax.DocumentHandler; -import org.xml.sax.EntityResolver; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.Parser; - -import java.util.Locale; - -/** - * A SAX Parser that can't be accessed. - */ -@SuppressWarnings("deprecation") -class NoAccessParser implements Parser { - - public void parse(InputSource source) { - } - - public void parse(String systemId) { - } - - public void setDocumentHandler(DocumentHandler handler) { - } - - public void setDTDHandler(DTDHandler handler) { - } - - public void setEntityResolver(EntityResolver resolver) { - } - - public void setErrorHandler(ErrorHandler handler) { - } - - public void setLocale(Locale locale) { - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/NoAccessXMLReader.java b/luni/src/test/java/tests/api/org/xml/sax/support/NoAccessXMLReader.java deleted file mode 100644 index b6a0a68..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/support/NoAccessXMLReader.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.support; - -import org.xml.sax.ContentHandler; -import org.xml.sax.DTDHandler; -import org.xml.sax.EntityResolver; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.XMLReader; - -/** - * An XMLReader that is not accessible. - */ -class NoAccessXMLReader implements XMLReader { - - public ContentHandler getContentHandler() { - return null; - } - - public DTDHandler getDTDHandler() { - return null; - } - - public EntityResolver getEntityResolver() { - return null; - } - - public ErrorHandler getErrorHandler() { - return null; - } - - public boolean getFeature(String name) { - return false; - } - - public Object getProperty(String name) { - return null; - } - - public void parse(InputSource input) { - } - - public void parse(String systemId) { - } - - public void setContentHandler(ContentHandler handler) { - } - - public void setDTDHandler(DTDHandler handler) { - } - - public void setEntityResolver(EntityResolver resolver) { - } - - public void setErrorHandler(ErrorHandler handler) { - } - - public void setFeature(String name, boolean value) { - } - - public void setProperty(String name, Object value) { - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/NoInstanceParser.java b/luni/src/test/java/tests/api/org/xml/sax/support/NoInstanceParser.java deleted file mode 100644 index 48cfba7..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/support/NoInstanceParser.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.support; - -import org.xml.sax.DTDHandler; -import org.xml.sax.DocumentHandler; -import org.xml.sax.EntityResolver; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.Parser; - -import java.util.Locale; - -/** - * A SAX Parser that can be accessed, but not instantiated. - */ -@SuppressWarnings("deprecation") -public class NoInstanceParser implements Parser { - - public NoInstanceParser(int i) { - } - - public void parse(InputSource source) { - } - - public void parse(String systemId) { - } - - public void setDocumentHandler(DocumentHandler handler) { - } - - public void setDTDHandler(DTDHandler handler) { - } - - public void setEntityResolver(EntityResolver resolver) { - } - - public void setErrorHandler(ErrorHandler handler) { - } - - public void setLocale(Locale locale) { - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/NoInstanceXMLReader.java b/luni/src/test/java/tests/api/org/xml/sax/support/NoInstanceXMLReader.java deleted file mode 100644 index 7b386bc..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/support/NoInstanceXMLReader.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.support; - -import org.xml.sax.ContentHandler; -import org.xml.sax.DTDHandler; -import org.xml.sax.EntityResolver; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.XMLReader; - -/** - * An XMLReader that is accessible, but can't be instantiated. - */ -public class NoInstanceXMLReader implements XMLReader { - - public NoInstanceXMLReader(int i) { - } - - public ContentHandler getContentHandler() { - return null; - } - - public DTDHandler getDTDHandler() { - return null; - } - - public EntityResolver getEntityResolver() { - return null; - } - - public ErrorHandler getErrorHandler() { - return null; - } - - public boolean getFeature(String name) { - return false; - } - - public Object getProperty(String name) { - return null; - } - - public void parse(InputSource input) { - } - - public void parse(String systemId) { - } - - public void setContentHandler(ContentHandler handler) { - } - - public void setDTDHandler(DTDHandler handler) { - } - - public void setEntityResolver(EntityResolver resolver) { - } - - public void setErrorHandler(ErrorHandler handler) { - } - - public void setFeature(String name, boolean value) { - } - - public void setProperty(String name, Object value) { - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/NoSubclassParser.java b/luni/src/test/java/tests/api/org/xml/sax/support/NoSubclassParser.java deleted file mode 100644 index 8016c10..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/support/NoSubclassParser.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.support; - -import org.xml.sax.DTDHandler; -import org.xml.sax.DocumentHandler; -import org.xml.sax.EntityResolver; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; - -import java.util.Locale; - -/** - * A SAX Parser that does not implement the Parser interface. - */ -@SuppressWarnings("deprecation") -public class NoSubclassParser { - - public void parse(InputSource source) { - } - - public void parse(String systemId) { - } - - public void setDocumentHandler(DocumentHandler handler) { - } - - public void setDTDHandler(DTDHandler handler) { - } - - public void setEntityResolver(EntityResolver resolver) { - } - - public void setErrorHandler(ErrorHandler handler) { - } - - public void setLocale(Locale locale) { - } - -} diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/NoSubclassXMLReader.java b/luni/src/test/java/tests/api/org/xml/sax/support/NoSubclassXMLReader.java deleted file mode 100644 index acdbd88..0000000 --- a/luni/src/test/java/tests/api/org/xml/sax/support/NoSubclassXMLReader.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2007 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 tests.api.org.xml.sax.support; - -import org.xml.sax.ContentHandler; -import org.xml.sax.DTDHandler; -import org.xml.sax.EntityResolver; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.XMLReader; - -/** - * An XMLReader that does not implement the XMLReader interface. - */ -public class NoSubclassXMLReader implements XMLReader { - - public ContentHandler getContentHandler() { - return null; - } - - public DTDHandler getDTDHandler() { - return null; - } - - public EntityResolver getEntityResolver() { - return null; - } - - public ErrorHandler getErrorHandler() { - return null; - } - - public boolean getFeature(String name) { - return false; - } - - public Object getProperty(String name) { - return null; - } - - public void parse(InputSource input) { - } - - public void parse(String systemId) { - } - - public void setContentHandler(ContentHandler handler) { - } - - public void setDTDHandler(DTDHandler handler) { - } - - public void setEntityResolver(EntityResolver resolver) { - } - - public void setErrorHandler(ErrorHandler handler) { - } - - public void setFeature(String name, boolean value) { - } - - public void setProperty(String name, Object value) { - } - -} diff --git a/luni/src/test/java/tests/java/sql/SqlDateTest.java b/luni/src/test/java/tests/java/sql/SqlDateTest.java new file mode 100644 index 0000000..fb226af --- /dev/null +++ b/luni/src/test/java/tests/java/sql/SqlDateTest.java @@ -0,0 +1,50 @@ +/* + * Copyright (C) 2014 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. + */ + +import java.sql.Date; + +import junit.framework.TestCase; + +public class SqlDateTest extends TestCase { + + public void testValueOf() { + String[] dates = { + "2001-12-31", "2001-12-1", "2001-1-1", "1900-12-31" + }; + + for (String date : dates) { + Date.valueOf(date); + } + } + + public void testValueOfInvalidDate() { + String[] invalidDates = { + "", + "+2001-12-31", "2001-+12-31", "2001-12-+31", + "-2001-12-31", "2001--12-31", "2001-12--31", + "2001--","2001--31","-12-31", "-12-", "--31", + "2000000001-12-31" + }; + + for (String date : invalidDates) { + try { + Date.valueOf(date); + fail(); + } catch (IllegalArgumentException expected) { } + } + } + +} diff --git a/luni/src/test/java/tests/security/cert/CertificateRevocationExceptionTest.java b/luni/src/test/java/tests/security/cert/CertificateRevocationExceptionTest.java new file mode 100644 index 0000000..c3894f8 --- /dev/null +++ b/luni/src/test/java/tests/security/cert/CertificateRevocationExceptionTest.java @@ -0,0 +1,167 @@ +/* + * Copyright 2014 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 tests.security.cert; + +import org.apache.harmony.testframework.serialization.SerializationTest; +import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; +import java.io.IOException; +import java.io.OutputStream; +import java.io.Serializable; +import java.security.cert.CRLReason; +import java.security.cert.CertificateRevokedException; +import java.security.cert.Extension; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import javax.security.auth.x500.X500Principal; + +import junit.framework.TestCase; + +/** + * + */ +public class CertificateRevocationExceptionTest extends TestCase implements SerializableAssert { + private CertificateRevokedException getTestException() { + HashMap<String, Extension> extensions = new HashMap<String, Extension>(); + // REASON_CODE + extensions.put("2.5.29.21", getReasonExtension()); + extensions.put("2.5.29.24", getInvalidityExtension()); + return new CertificateRevokedException( + new Date(1199226851000L), + CRLReason.CESSATION_OF_OPERATION, + new X500Principal("CN=test1"), + extensions); + } + + private Extension getReasonExtension() { + return new Extension() { + @Override + public String getId() { + return "2.5.29.21"; + } + + @Override + public boolean isCritical() { + return false; + } + + @Override + public byte[] getValue() { + return new byte[] {4, 3, 10, 1, 5}; + } + + @Override + public void encode(OutputStream out) throws IOException { + throw new UnsupportedOperationException(); + } + }; + } + + private Extension getInvalidityExtension() { + return new Extension() { + @Override + public String getId() { + return "2.5.29.24"; + } + + @Override + public boolean isCritical() { + return false; + } + + @Override + public byte[] getValue() { + return new byte[] { + 0x18, 0x0F, 0x32, 0x30, 0x31, 0x34, 0x30, 0x31, 0x31, 0x37, 0x30, 0x38, + 0x33, 0x30, 0x30, 0x39, 0x5a + }; + } + + @Override + public void encode(OutputStream out) throws IOException { + throw new UnsupportedOperationException(); + } + }; + } + + public void testGetExtensions() throws Exception { + CertificateRevokedException original = getTestException(); + Map<String, Extension> extensions = original.getExtensions(); + assertNotSame(extensions, original.getExtensions()); + + try { + extensions.put("2.2.2.2", getReasonExtension()); + fail(); + } catch (UnsupportedOperationException expected) { + } + } + + public void testGetRevocationDate() throws Exception { + CertificateRevokedException exception = getTestException(); + + Date firstDate = exception.getRevocationDate(); + assertNotSame(firstDate, exception.getRevocationDate()); + + firstDate.setYear(firstDate.getYear() + 1); + assertTrue(firstDate.compareTo(exception.getRevocationDate()) > 0); + } + + public void testGetInvalidityDate() throws Exception { + CertificateRevokedException exception = getTestException(); + + Date firstDate = exception.getInvalidityDate(); + assertNotSame(firstDate, exception.getInvalidityDate()); + + firstDate.setYear(firstDate.getYear() + 1); + assertTrue(firstDate.compareTo(exception.getInvalidityDate()) > 0); + } + + + /** + * serialization/deserialization compatibility. + */ + public void testSerializationCertificateRevokedExceptionSelf() throws Exception { + SerializationTest.verifySelf(getTestException(), this); + } + + /** + * serialization/deserialization compatibility with RI. + */ + public void testSerializationCertificateRevokedExceptionCompatability() throws Exception { + // create test file (once) + // SerializationTest.createGoldenFile("/tmp", this, getTestException()); + SerializationTest.verifyGolden(this, getTestException()); + } + + @Override + public void assertDeserialized(Serializable initial, Serializable deserialized) { + assertTrue(initial instanceof CertificateRevokedException); + assertTrue(deserialized instanceof CertificateRevokedException); + + CertificateRevokedException expected = (CertificateRevokedException) initial; + CertificateRevokedException actual = (CertificateRevokedException) deserialized; + + assertEquals(expected.getInvalidityDate(), actual.getInvalidityDate()); + assertNotSame(expected.getInvalidityDate(), actual.getInvalidityDate()); + assertEquals(expected.getRevocationDate(), actual.getRevocationDate()); + assertNotSame(expected.getRevocationDate(), actual.getRevocationDate()); + assertEquals(expected.getRevocationReason(), expected.getRevocationReason()); + + assertEquals(expected.getExtensions().size(), actual.getExtensions().size()); + assertEquals(expected.getExtensions().keySet(), actual.getExtensions().keySet()); + } +} |