ClassTest.java revision 89c1feb0a69a7707b271086e749975b3f7acacf7
1/*
2 *  Licensed to the Apache Software Foundation (ASF) under one or more
3 *  contributor license agreements.  See the NOTICE file distributed with
4 *  this work for additional information regarding copyright ownership.
5 *  The ASF licenses this file to You under the Apache License, Version 2.0
6 *  (the "License"); you may not use this file except in compliance with
7 *  the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 */
17
18package org.apache.harmony.luni.tests.java.lang;
19
20import dalvik.annotation.TestInfo;
21import dalvik.annotation.TestLevel;
22import dalvik.annotation.TestTarget;
23import dalvik.annotation.TestTargetClass;
24
25import java.io.File;
26import java.io.FileInputStream;
27import java.io.InputStream;
28import java.io.Serializable;
29import java.lang.reflect.Constructor;
30import java.lang.reflect.Field;
31import java.lang.reflect.Member;
32import java.lang.reflect.Method;
33import java.lang.reflect.Modifier;
34import java.net.URL;
35import java.net.URLClassLoader;
36import java.security.AccessControlContext;
37import java.security.AccessController;
38import java.security.BasicPermission;
39import java.security.DomainCombiner;
40import java.security.Permission;
41import java.security.PrivilegedAction;
42import java.security.ProtectionDomain;
43import java.security.Security;
44import java.util.Arrays;
45import java.util.List;
46import java.util.Vector;
47
48import tests.support.resource.Support_Resources;
49
50@TestTargetClass(Class.class)
51public class ClassTest extends junit.framework.TestCase {
52
53    /*
54     * TODO(Fixed) Harmony seems to assume that packages are always defined.
55     * This isn't (currently) true for our VM and it also isn't required by
56     * the Java spec. Thus we get the package name a different way.
57     */
58    public static final String FILENAME = getPackageName(); // ClassTest.class.getPackage().getName().replace('.', '/')+"/test#.properties";
59
60    static String getPackageName() {
61        String s = ClassTest.class.getName();
62        int dot = s.lastIndexOf('.');
63        return s.substring(0, dot).replace('.', '/')+"/test#.properties";
64    }
65
66    static class StaticMember$Class {
67        class Member2$A {
68        }
69    }
70
71    class Member$Class {
72        class Member3$B {
73        }
74    }
75
76    public static class TestClass {
77        @SuppressWarnings("unused")
78        private int privField = 1;
79
80        public int pubField = 2;
81
82        private Object cValue = null;
83
84        public Object ack = new Object();
85
86        @SuppressWarnings("unused")
87        private int privMethod() {
88            return 1;
89        }
90
91        public int pubMethod() {
92            return 2;
93        }
94
95        public Object cValue() {
96            return cValue;
97        }
98
99        public TestClass() {
100        }
101
102        @SuppressWarnings("unused")
103        private TestClass(Object o) {
104        }
105    }
106
107    public static class SubTestClass extends TestClass {
108    }
109
110    /**
111     * @tests java.lang.Class#forName(java.lang.String)
112     */
113    @TestInfo(
114      level = TestLevel.PARTIAL,
115      purpose = "ExceptionInInitializerError is not tested, if it's possible.",
116      targets = {
117        @TestTarget(
118          methodName = "forName",
119          methodArgs = {java.lang.String.class}
120        )
121    })
122    public void test_forNameLjava_lang_String() throws Exception {
123        assertSame("Class for name failed for java.lang.Object",
124                   Object.class, Class.forName("java.lang.Object"));
125        assertSame("Class for name failed for [[Ljava.lang.Object;",
126                   Object[][].class, Class.forName("[[Ljava.lang.Object;"));
127
128        assertSame("Class for name failed for [I",
129                   int[].class, Class.forName("[I"));
130
131        try {
132            Class.forName("int");
133            fail();
134        } catch (ClassNotFoundException e) {
135        }
136
137        try {
138            Class.forName("byte");
139            fail();
140        } catch (ClassNotFoundException e) {
141        }
142        try {
143            Class.forName("char");
144            fail();
145        } catch (ClassNotFoundException e) {
146        }
147
148        try {
149            Class.forName("void");
150            fail();
151        } catch (ClassNotFoundException e) {
152        }
153
154        try {
155            Class.forName("short");
156            fail();
157        } catch (ClassNotFoundException e) {
158        }
159        try {
160            Class.forName("long");
161            fail();
162        } catch (ClassNotFoundException e) {
163        }
164
165        try {
166            Class.forName("boolean");
167            fail();
168        } catch (ClassNotFoundException e) {
169        }
170        try {
171            Class.forName("float");
172            fail();
173        } catch (ClassNotFoundException e) {
174        }
175        try {
176            Class.forName("double");
177            fail();
178        } catch (ClassNotFoundException e) {
179        }
180
181        //regression test for JIRA 2162
182        try {
183            Class.forName("%");
184            fail("should throw ClassNotFoundException.");
185        } catch (ClassNotFoundException e) {
186        }
187
188        //Regression Test for HARMONY-3332
189        String securityProviderClassName;
190        int count = 1;
191        while ((securityProviderClassName = Security
192                .getProperty("security.provider." + count++)) != null) {
193            Class.forName(securityProviderClassName);
194        }
195    }
196
197    /**
198     * @tests java.lang.Class#getClasses()
199     */
200    @TestInfo(
201      level = TestLevel.COMPLETE,
202      purpose = "",
203      targets = {
204        @TestTarget(
205          methodName = "getClasses",
206          methodArgs = {}
207        )
208    })
209    public void test_getClasses() {
210        assertEquals("Incorrect class array returned",
211                     2, ClassTest.class.getClasses().length);
212    }
213
214    /**
215     * @tests java.lang.Class#getClasses()
216     */
217    @TestInfo(
218      level = TestLevel.COMPLETE,
219      purpose = "",
220      targets = {
221        @TestTarget(
222          methodName = "getClasses",
223          methodArgs = {}
224        )
225    })
226    public void _test_getClasses_subtest0() {
227        final Permission privCheckPermission = new BasicPermission("Privilege check") {
228            private static final long serialVersionUID = 1L;
229        };
230
231        class MyCombiner implements DomainCombiner {
232            boolean combine;
233
234            public ProtectionDomain[] combine(ProtectionDomain[] executionDomains,
235                    ProtectionDomain[] parentDomains) {
236                combine = true;
237                return new ProtectionDomain[0];
238            }
239
240            private boolean recurring = false;
241
242            public boolean isPriviledged() {
243                if (recurring) {
244                    return true;
245                }
246                try {
247                    recurring = true;
248                    combine = false;
249                    try {
250                        AccessController.checkPermission(privCheckPermission);
251                    } catch (SecurityException e) {}
252                    return !combine;
253                } finally {
254                    recurring = false;
255                }
256            }
257        }
258
259        final MyCombiner combiner = new MyCombiner();
260        class SecurityManagerCheck extends SecurityManager {
261            String reason;
262
263            Class<?> checkClass;
264
265            int checkType;
266
267            int checkPermission;
268
269            int checkMemberAccess;
270
271            int checkPackageAccess;
272
273            public void setExpected(String reason, Class<?> cls, int type) {
274                this.reason = reason;
275                checkClass = cls;
276                checkType = type;
277                checkPermission = 0;
278                checkMemberAccess = 0;
279                checkPackageAccess = 0;
280            }
281
282            @Override
283            public void checkPermission(Permission perm) {
284                if (combiner.isPriviledged())
285                    return;
286                checkPermission++;
287            }
288
289            @Override
290            public void checkMemberAccess(Class<?> cls, int type) {
291                if (combiner.isPriviledged())
292                    return;
293                checkMemberAccess++;
294                assertEquals(reason + " unexpected class", checkClass, cls);
295                assertEquals(reason + "unexpected type", checkType, type);
296            }
297
298            @Override
299            public void checkPackageAccess(String packageName) {
300                if (combiner.isPriviledged())
301                    return;
302                checkPackageAccess++;
303                String name = checkClass.getName();
304                int index = name.lastIndexOf('.');
305                String checkPackage = name.substring(0, index);
306                assertEquals(reason + " unexpected package",
307                             checkPackage,  packageName);
308            }
309
310            public void assertProperCalls() {
311                assertEquals(reason + " unexpected checkPermission count",
312                             0, checkPermission);
313                assertEquals(reason + " unexpected checkMemberAccess count",
314                             1, checkMemberAccess);
315                assertEquals(reason + " unexpected checkPackageAccess count",
316                             1, checkPackageAccess);
317            }
318        }
319
320        AccessControlContext acc = new AccessControlContext(new ProtectionDomain[0]);
321        AccessControlContext acc2 = new AccessControlContext(acc, combiner);
322
323        PrivilegedAction<?> action = new PrivilegedAction<Object>() {
324            public Object run() {
325                File resources = Support_Resources.createTempFolder();
326                try {
327                    Support_Resources.copyFile(resources, null, "hyts_security.jar");
328                    File file = new File(resources.toString() + "/hyts_security.jar");
329                    URL url = new URL("file:" + file.getPath());
330                    ClassLoader loader = new URLClassLoader(new URL[] { url }, null);
331                    Class<?> cls = Class.forName("packB.SecurityTestSub", false, loader);
332                    SecurityManagerCheck sm = new SecurityManagerCheck();
333                    System.setSecurityManager(sm);
334                    try {
335                        sm.setExpected("getClasses", cls, Member.PUBLIC);
336                        cls.getClasses();
337                        sm.assertProperCalls();
338
339                        sm.setExpected("getDeclaredClasses", cls, Member.DECLARED);
340                        cls.getDeclaredClasses();
341                        sm.assertProperCalls();
342
343                        sm.setExpected("getConstructor", cls, Member.PUBLIC);
344                        cls.getConstructor(new Class[0]);
345                        sm.assertProperCalls();
346
347                        sm.setExpected("getConstructors", cls, Member.PUBLIC);
348                        cls.getConstructors();
349                        sm.assertProperCalls();
350
351                        sm.setExpected("getDeclaredConstructor", cls, Member.DECLARED);
352                        cls.getDeclaredConstructor(new Class[0]);
353                        sm.assertProperCalls();
354
355                        sm.setExpected("getDeclaredConstructors", cls, Member.DECLARED);
356                        cls.getDeclaredConstructors();
357                        sm.assertProperCalls();
358
359                        sm.setExpected("getField", cls, Member.PUBLIC);
360                        cls.getField("publicField");
361                        sm.assertProperCalls();
362
363                        sm.setExpected("getFields", cls, Member.PUBLIC);
364                        cls.getFields();
365                        sm.assertProperCalls();
366
367                        sm.setExpected("getDeclaredField", cls, Member.DECLARED);
368                        cls.getDeclaredField("publicField");
369                        sm.assertProperCalls();
370
371                        sm.setExpected("getDeclaredFields", cls, Member.DECLARED);
372                        cls.getDeclaredFields();
373                        sm.assertProperCalls();
374
375                        sm.setExpected("getDeclaredMethod", cls, Member.DECLARED);
376                        cls.getDeclaredMethod("publicMethod", new Class[0]);
377                        sm.assertProperCalls();
378
379                        sm.setExpected("getDeclaredMethods", cls, Member.DECLARED);
380                        cls.getDeclaredMethods();
381                        sm.assertProperCalls();
382
383                        sm.setExpected("getMethod", cls, Member.PUBLIC);
384                        cls.getMethod("publicMethod", new Class[0]);
385                        sm.assertProperCalls();
386
387                        sm.setExpected("getMethods", cls, Member.PUBLIC);
388                        cls.getMethods();
389                        sm.assertProperCalls();
390
391                        sm.setExpected("newInstance", cls, Member.PUBLIC);
392                        cls.newInstance();
393                        sm.assertProperCalls();
394                    } finally {
395                        System.setSecurityManager(null);
396                    }
397                } catch (Exception e) {
398                    if (e instanceof RuntimeException)
399                        throw (RuntimeException) e;
400                    fail("unexpected exception: " + e);
401                }
402                return null;
403            }
404        };
405        AccessController.doPrivileged(action, acc2);
406    }
407
408    /**
409     * @tests java.lang.Class#getComponentType()
410     */
411    @TestInfo(
412      level = TestLevel.COMPLETE,
413      purpose = "",
414      targets = {
415        @TestTarget(
416          methodName = "getComponentType",
417          methodArgs = {}
418        )
419    })
420    public void test_getComponentType() {
421        assertSame("int array does not have int component type", int.class, int[].class
422                .getComponentType());
423        assertSame("Object array does not have Object component type", Object.class,
424                Object[].class.getComponentType());
425        assertNull("Object has non-null component type", Object.class.getComponentType());
426    }
427
428    /**
429     * @tests java.lang.Class#getConstructor(java.lang.Class[])
430     */
431    @TestInfo(
432      level = TestLevel.PARTIAL,
433      purpose = "Doesn't verify positive functionality and SecurityException.",
434      targets = {
435        @TestTarget(
436          methodName = "getConstructor",
437          methodArgs = {java.lang.Class[].class}
438        )
439    })
440    public void test_getConstructor$Ljava_lang_Class()
441        throws NoSuchMethodException {
442        TestClass.class.getConstructor(new Class[0]);
443        try {
444            TestClass.class.getConstructor(Object.class);
445            fail("Found private constructor");
446        } catch (NoSuchMethodException e) {
447            // Correct - constructor with obj is private
448        }
449    }
450
451    /**
452     * @tests java.lang.Class#getConstructors()
453     */
454    @TestInfo(
455      level = TestLevel.PARTIAL,
456      purpose = "Doesn't verify SecurityException.",
457      targets = {
458        @TestTarget(
459          methodName = "getConstructors",
460          methodArgs = {}
461        )
462    })
463    public void test_getConstructors() throws Exception {
464        Constructor[] c = TestClass.class.getConstructors();
465        assertEquals("Incorrect number of constructors returned", 1, c.length);
466    }
467
468    /**
469     * @tests java.lang.Class#getDeclaredClasses()
470     */
471    @TestInfo(
472      level = TestLevel.TODO,
473      purpose = "Doesn't verify getDeclaredClasses method.",
474      targets = {
475        @TestTarget(
476          methodName = "getDeclaredClasses",
477          methodArgs = {}
478        )
479    })
480    public void test_getDeclaredClasses() {
481        assertEquals("Incorrect class array returned", 2, ClassTest.class.getClasses().length);
482    }
483
484    /**
485     * @tests java.lang.Class#getDeclaredConstructor(java.lang.Class[])
486     */
487    @TestInfo(
488      level = TestLevel.PARTIAL,
489      purpose = "NoSuchMethodException, SecurityException are not verified.",
490      targets = {
491        @TestTarget(
492          methodName = "getDeclaredConstructor",
493          methodArgs = {java.lang.Class[].class}
494        )
495    })
496    public void test_getDeclaredConstructor$Ljava_lang_Class() throws Exception {
497        Constructor<TestClass> c = TestClass.class.getDeclaredConstructor(new Class[0]);
498        assertNull("Incorrect constructor returned", c.newInstance().cValue());
499        c = TestClass.class.getDeclaredConstructor(Object.class);
500    }
501
502    /**
503     * @tests java.lang.Class#getDeclaredConstructors()
504     */
505    @TestInfo(
506      level = TestLevel.PARTIAL,
507      purpose = "SecurityException is not verified.",
508      targets = {
509        @TestTarget(
510          methodName = "getDeclaredConstructors",
511          methodArgs = {}
512        )
513    })
514    public void test_getDeclaredConstructors() throws Exception {
515        Constructor[] c = TestClass.class.getDeclaredConstructors();
516        assertEquals("Incorrect number of constructors returned", 2, c.length);
517    }
518
519    /**
520     * @tests java.lang.Class#getDeclaredField(java.lang.String)
521     */
522    @TestInfo(
523      level = TestLevel.PARTIAL,
524      purpose = "Exceptions are not verified.",
525      targets = {
526        @TestTarget(
527          methodName = "getDeclaredField",
528          methodArgs = {java.lang.String.class}
529        )
530    })
531    public void test_getDeclaredFieldLjava_lang_String() throws Exception {
532        Field f = TestClass.class.getDeclaredField("pubField");
533        assertEquals("Returned incorrect field", 2, f.getInt(new TestClass()));
534    }
535
536    /**
537     * @tests java.lang.Class#getDeclaredFields()
538     */
539    @TestInfo(
540      level = TestLevel.PARTIAL,
541      purpose = "Exceptions are not verified.",
542      targets = {
543        @TestTarget(
544          methodName = "getDeclaredFields",
545          methodArgs = {}
546        )
547    })
548    public void test_getDeclaredFields() throws Exception {
549        Field[] f = TestClass.class.getDeclaredFields();
550        assertEquals("Returned incorrect number of fields", 4, f.length);
551        f = SubTestClass.class.getDeclaredFields();
552        // Declared fields do not include inherited
553        assertEquals("Returned incorrect number of fields", 0, f.length);
554    }
555
556    /**
557     * @tests java.lang.Class#getDeclaredMethod(java.lang.String,
558     *        java.lang.Class[])
559     */
560    @TestInfo(
561      level = TestLevel.PARTIAL,
562      purpose = "Exceptions are not tested.",
563      targets = {
564        @TestTarget(
565          methodName = "getDeclaredMethod",
566          methodArgs = {java.lang.String.class, java.lang.Class[].class}
567        )
568    })
569    public void test_getDeclaredMethodLjava_lang_String$Ljava_lang_Class() throws Exception {
570        Method m = TestClass.class.getDeclaredMethod("pubMethod", new Class[0]);
571        assertEquals("Returned incorrect method", 2, ((Integer) (m.invoke(new TestClass())))
572                .intValue());
573        m = TestClass.class.getDeclaredMethod("privMethod", new Class[0]);
574    }
575
576    /**
577     * @tests java.lang.Class#getDeclaredMethods()
578     */
579    @TestInfo(
580      level = TestLevel.PARTIAL,
581      purpose = "SecurityException is not verified.",
582      targets = {
583        @TestTarget(
584          methodName = "getDeclaredMethods",
585          methodArgs = {}
586        )
587    })
588    public void test_getDeclaredMethods() throws Exception {
589        Method[] m = TestClass.class.getDeclaredMethods();
590        assertEquals("Returned incorrect number of methods", 3, m.length);
591        m = SubTestClass.class.getDeclaredMethods();
592        assertEquals("Returned incorrect number of methods", 0, m.length);
593    }
594
595    /**
596     * @tests java.lang.Class#getDeclaringClass()
597     */
598    @TestInfo(
599      level = TestLevel.PARTIAL,
600      purpose = "Simple test.",
601      targets = {
602        @TestTarget(
603          methodName = "getDeclaringClass",
604          methodArgs = {}
605        )
606    })
607    public void test_getDeclaringClass() {
608        assertEquals(ClassTest.class, TestClass.class.getDeclaringClass());
609    }
610
611    /**
612     * @tests java.lang.Class#getField(java.lang.String)
613     */
614    @TestInfo(
615      level = TestLevel.PARTIAL,
616      purpose = "NullPointerException, SecurityException are not verified.",
617      targets = {
618        @TestTarget(
619          methodName = "getField",
620          methodArgs = {java.lang.String.class}
621        )
622    })
623    public void test_getFieldLjava_lang_String() throws Exception {
624        Field f = TestClass.class.getField("pubField");
625        assertEquals("Returned incorrect field", 2, f.getInt(new TestClass()));
626        try {
627            f = TestClass.class.getField("privField");
628            fail("Private field access failed to throw exception");
629        } catch (NoSuchFieldException e) {
630            // Correct
631        }
632    }
633
634    /**
635     * @tests java.lang.Class#getFields()
636     */
637    @TestInfo(
638      level = TestLevel.PARTIAL,
639      purpose = "SecurityException is not tested.",
640      targets = {
641        @TestTarget(
642          methodName = "getFields",
643          methodArgs = {}
644        )
645    })
646    public void test_getFields() throws Exception {
647        Field[] f = TestClass.class.getFields();
648        assertEquals("Incorrect number of fields", 2, f.length);
649        f = SubTestClass.class.getFields();
650        // Check inheritance of pub fields
651        assertEquals("Incorrect number of fields", 2, f.length);
652    }
653
654    /**
655     * @tests java.lang.Class#getInterfaces()
656     */
657    @TestInfo(
658      level = TestLevel.COMPLETE,
659      purpose = "",
660      targets = {
661        @TestTarget(
662          methodName = "getInterfaces",
663          methodArgs = {}
664        )
665    })
666    public void test_getInterfaces() {
667        Class[] interfaces;
668        List<?> interfaceList;
669        interfaces = Object.class.getInterfaces();
670        assertEquals("Incorrect interface list for Object", 0, interfaces.length);
671        interfaceList = Arrays.asList(Vector.class.getInterfaces());
672        assertTrue("Incorrect interface list for Vector", interfaceList
673                .contains(Cloneable.class)
674                && interfaceList.contains(Serializable.class)
675                && interfaceList.contains(List.class));
676    }
677
678    /**
679     * @tests java.lang.Class#getMethod(java.lang.String, java.lang.Class[])
680     */
681    @TestInfo(
682      level = TestLevel.PARTIAL,
683      purpose = "NullPointerException, SecurityException are not verified.",
684      targets = {
685        @TestTarget(
686          methodName = "getMethod",
687          methodArgs = {java.lang.String.class, java.lang.Class[].class}
688        )
689    })
690    public void test_getMethodLjava_lang_String$Ljava_lang_Class() throws Exception {
691        Method m = TestClass.class.getMethod("pubMethod", new Class[0]);
692        assertEquals("Returned incorrect method", 2, ((Integer) (m.invoke(new TestClass())))
693                .intValue());
694        try {
695            m = TestClass.class.getMethod("privMethod", new Class[0]);
696            fail("Failed to throw exception accessing private method");
697        } catch (NoSuchMethodException e) {
698            // Correct
699            return;
700        }
701    }
702
703    /**
704     * @tests java.lang.Class#getMethods()
705     */
706    @TestInfo(
707      level = TestLevel.PARTIAL,
708      purpose = "SecurityException is not tested.",
709      targets = {
710        @TestTarget(
711          methodName = "getMethods",
712          methodArgs = {}
713        )
714    })
715    public void test_getMethods() throws Exception {
716        Method[] m = TestClass.class.getMethods();
717        assertEquals("Returned incorrect number of methods",
718                     2 + Object.class.getMethods().length, m.length);
719        m = SubTestClass.class.getMethods();
720        assertEquals("Returned incorrect number of sub-class methods",
721                     2 + Object.class.getMethods().length, m.length);
722        // Number of inherited methods
723    }
724
725    private static final class PrivateClass {
726    }
727    /**
728     * @tests java.lang.Class#getModifiers()
729     */
730    @TestInfo(
731      level = TestLevel.COMPLETE,
732      purpose = "",
733      targets = {
734        @TestTarget(
735          methodName = "getModifiers",
736          methodArgs = {}
737        )
738    })
739    public void test_getModifiers() {
740        int dcm = PrivateClass.class.getModifiers();
741        assertFalse("default class is public", Modifier.isPublic(dcm));
742        assertFalse("default class is protected", Modifier.isProtected(dcm));
743        assertTrue("default class is not private", Modifier.isPrivate(dcm));
744
745        int ocm = Object.class.getModifiers();
746        assertTrue("public class is not public", Modifier.isPublic(ocm));
747        assertFalse("public class is protected", Modifier.isProtected(ocm));
748        assertFalse("public class is private", Modifier.isPrivate(ocm));
749    }
750
751    /**
752     * @tests java.lang.Class#getName()
753     */
754    @TestInfo(
755      level = TestLevel.COMPLETE,
756      purpose = "",
757      targets = {
758        @TestTarget(
759          methodName = "getName",
760          methodArgs = {}
761        )
762    })
763    public void test_getName() throws Exception {
764        String className = Class.forName("java.lang.Object").getName();
765        assertNotNull(className);
766
767        assertEquals("Class getName printed wrong value", "java.lang.Object", className);
768        assertEquals("Class getName printed wrong value", "int", int.class.getName());
769        className = Class.forName("[I").getName();
770        assertNotNull(className);
771        assertEquals("Class getName printed wrong value", "[I", className);
772
773        className = Class.forName("[Ljava.lang.Object;").getName();
774        assertNotNull(className);
775
776        assertEquals("Class getName printed wrong value", "[Ljava.lang.Object;", className);
777    }
778
779    /**
780     * @tests java.lang.Class#getResource(java.lang.String)
781     */
782    @TestInfo(
783      level = TestLevel.PARTIAL,
784      purpose = "",
785      targets = {
786        @TestTarget(
787          methodName = "getResource",
788          methodArgs = {java.lang.String.class}
789        )
790    })
791    public void test_getResourceLjava_lang_String() {
792        final String name = "/org/apache/harmony/luni/tests/java/lang/HelloWorld.txt";
793        URL res = getClass().getResource(name);
794        assertNotNull(res);
795    }
796
797    /**
798     * @tests java.lang.Class#getResourceAsStream(java.lang.String)
799     */
800    @TestInfo(
801      level = TestLevel.PARTIAL,
802      purpose = "NullPointerException is not verified.",
803      targets = {
804        @TestTarget(
805          methodName = "getResourceAsStream",
806          methodArgs = {java.lang.String.class}
807        )
808    })
809    public void _test_getResourceAsStreamLjava_lang_String() throws Exception {
810        final String name = "/org/apache/harmony/luni/tests/test_resource.txt";
811        assertNotNull("the file " + name + " can not be found in this directory", getClass()
812                .getResourceAsStream(name));
813
814        final String nameBadURI = "org/apache/harmony/luni/tests/test_resource.txt";
815        assertNull("the file " + nameBadURI + " should not be found in this directory",
816                getClass().getResourceAsStream(nameBadURI));
817
818        InputStream str = Object.class.getResourceAsStream("Class.class");
819        assertNotNull("java.lang.Object couldn't find its class with getResource...", str);
820
821        assertTrue("Cannot read single byte", str.read() != -1);
822        assertEquals("Cannot read multiple bytes", 5, str.read(new byte[5]));
823        str.close();
824
825        InputStream str2 = getClass().getResourceAsStream("ClassTest.class");
826        assertNotNull("Can't find resource", str2);
827        assertTrue("Cannot read single byte", str2.read() != -1);
828        assertEquals("Cannot read multiple bytes", 5, str2.read(new byte[5]));
829        str2.close();
830    }
831
832    /**
833     * @tests java.lang.Class#getSuperclass()
834     */
835    @TestInfo(
836      level = TestLevel.COMPLETE,
837      purpose = "",
838      targets = {
839        @TestTarget(
840          methodName = "getSuperclass",
841          methodArgs = {}
842        )
843    })
844    public void test_getSuperclass() {
845        assertNull("Object has a superclass???", Object.class.getSuperclass());
846        assertSame("Normal class has bogus superclass", InputStream.class,
847                FileInputStream.class.getSuperclass());
848        assertSame("Array class has bogus superclass", Object.class, FileInputStream[].class
849                .getSuperclass());
850        assertNull("Base class has a superclass", int.class.getSuperclass());
851        assertNull("Interface class has a superclass", Cloneable.class.getSuperclass());
852    }
853
854    /**
855     * @tests java.lang.Class#isArray()
856     */
857    @TestInfo(
858      level = TestLevel.COMPLETE,
859      purpose = "",
860      targets = {
861        @TestTarget(
862          methodName = "isArray",
863          methodArgs = {}
864        )
865    })
866    public void test_isArray() throws ClassNotFoundException {
867        assertTrue("Non-array type claims to be.", !int.class.isArray());
868        Class<?> clazz = null;
869        clazz = Class.forName("[I");
870        assertTrue("int Array type claims not to be.", clazz.isArray());
871
872        clazz = Class.forName("[Ljava.lang.Object;");
873        assertTrue("Object Array type claims not to be.", clazz.isArray());
874
875        clazz = Class.forName("java.lang.Object");
876        assertTrue("Non-array Object type claims to be.", !clazz.isArray());
877    }
878
879    /**
880     * @tests java.lang.Class#isAssignableFrom(java.lang.Class)
881     */
882    @TestInfo(
883      level = TestLevel.PARTIAL,
884      purpose = "NullPointerException is not verified.",
885      targets = {
886        @TestTarget(
887          methodName = "isAssignableFrom",
888          methodArgs = {java.lang.Class.class}
889        )
890    })
891    public void test_isAssignableFromLjava_lang_Class() {
892        Class<?> clazz1 = null;
893        Class<?> clazz2 = null;
894
895        clazz1 = Object.class;
896        clazz2 = Class.class;
897        assertTrue("returned false for superclass", clazz1.isAssignableFrom(clazz2));
898
899        clazz1 = TestClass.class;
900        assertTrue("returned false for same class", clazz1.isAssignableFrom(clazz1));
901
902        clazz1 = Runnable.class;
903        clazz2 = Thread.class;
904        assertTrue("returned false for implemented interface", clazz1.isAssignableFrom(clazz2));
905    }
906
907    /**
908     * @tests java.lang.Class#isInterface()
909     */
910    @TestInfo(
911      level = TestLevel.COMPLETE,
912      purpose = "",
913      targets = {
914        @TestTarget(
915          methodName = "isInterface",
916          methodArgs = {}
917        )
918    })
919    public void test_isInterface() throws ClassNotFoundException {
920        assertTrue("Prim type claims to be interface.", !int.class.isInterface());
921        Class<?> clazz = null;
922        clazz = Class.forName("[I");
923        assertTrue("Prim Array type claims to be interface.", !clazz.isInterface());
924
925        clazz = Class.forName("java.lang.Runnable");
926        assertTrue("Interface type claims not to be interface.", clazz.isInterface());
927        clazz = Class.forName("java.lang.Object");
928        assertTrue("Object type claims to be interface.", !clazz.isInterface());
929
930        clazz = Class.forName("[Ljava.lang.Object;");
931        assertTrue("Array type claims to be interface.", !clazz.isInterface());
932    }
933
934    /**
935     * @tests java.lang.Class#isPrimitive()
936     */
937    @TestInfo(
938      level = TestLevel.COMPLETE,
939      purpose = "",
940      targets = {
941        @TestTarget(
942          methodName = "isPrimitive",
943          methodArgs = {}
944        )
945    })
946    public void test_isPrimitive() {
947        assertFalse("Interface type claims to be primitive.", Runnable.class.isPrimitive());
948        assertFalse("Object type claims to be primitive.", Object.class.isPrimitive());
949        assertFalse("Prim Array type claims to be primitive.", int[].class.isPrimitive());
950        assertFalse("Array type claims to be primitive.", Object[].class.isPrimitive());
951        assertTrue("Prim type claims not to be primitive.", int.class.isPrimitive());
952        assertFalse("Object type claims to be primitive.", Object.class.isPrimitive());
953    }
954
955    /**
956     * @tests java.lang.Class#newInstance()
957     */
958    @TestInfo(
959      level = TestLevel.COMPLETE,
960      purpose = "",
961      targets = {
962        @TestTarget(
963          methodName = "newInstance",
964          methodArgs = {}
965        )
966    })
967    public void test_newInstance() throws Exception {
968        Class<?> clazz = null;
969        clazz = Class.forName("java.lang.Object");
970        assertNotNull("new object instance was null", clazz.newInstance());
971
972        clazz = Class.forName("java.lang.Throwable");
973        assertSame("new Throwable instance was not a throwable",
974                   clazz, clazz.newInstance().getClass());
975
976        clazz = Class.forName("java.lang.Integer");
977        try {
978            clazz.newInstance();
979            fail("Exception for instantiating a newInstance with no default constructor is not thrown");
980        } catch (InstantiationException e) {
981            // expected
982        }
983    }
984
985    /**
986     * @tests java.lang.Class#toString()
987     */
988    @TestInfo(
989      level = TestLevel.COMPLETE,
990      purpose = "",
991      targets = {
992        @TestTarget(
993          methodName = "toString",
994          methodArgs = {}
995        )
996    })
997    public void test_toString() throws ClassNotFoundException {
998        assertEquals("Class toString printed wrong value",
999                     "int", int.class.toString());
1000        Class<?> clazz = null;
1001        clazz = Class.forName("[I");
1002        assertEquals("Class toString printed wrong value",
1003                     "class [I", clazz.toString());
1004
1005        clazz = Class.forName("java.lang.Object");
1006        assertEquals("Class toString printed wrong value",
1007                     "class java.lang.Object", clazz.toString());
1008
1009        clazz = Class.forName("[Ljava.lang.Object;");
1010        assertEquals("Class toString printed wrong value",
1011                     "class [Ljava.lang.Object;", clazz.toString());
1012    }
1013
1014    @TestInfo(
1015      level = TestLevel.PARTIAL,
1016      purpose = "NullPointerException is not verified.",
1017      targets = {
1018        @TestTarget(
1019          methodName = "getResourceAsStream",
1020          methodArgs = {java.lang.String.class}
1021        )
1022    })
1023    // Regression Test for JIRA-2047
1024    public void _test_getResourceAsStream_withSharpChar() throws Exception{
1025        InputStream in = getClass().getResourceAsStream("/"+FILENAME);
1026        assertNotNull(in);
1027        in.close();
1028
1029        in = getClass().getResourceAsStream(FILENAME);
1030        assertNull(in);
1031
1032        in = this.getClass().getClassLoader().getResourceAsStream(
1033                FILENAME);
1034        assertNotNull(in);
1035        in.close();
1036    }
1037
1038        /*
1039         * Regression test for HARMONY-2644:
1040         * Load system and non-system array classes via Class.forName()
1041         */
1042        @TestInfo(
1043                level = TestLevel.PARTIAL,
1044                purpose = "LinkageError, ExceptionInInitializerError are " +
1045                        "not verified.",
1046                targets = {
1047                        @TestTarget(
1048                                methodName = "forName",
1049                                methodArgs = {java.lang.String.class}
1050                        )
1051        })
1052        public void _test_forName_arrays() throws Exception {
1053            Class c1 = getClass();
1054            String s = c1.getName();
1055            Class a1 = Class.forName("[L" + s + ";");
1056            Class a2 = Class.forName("[[L" + s + ";");
1057            assertSame(c1, a1.getComponentType());
1058            assertSame(a1, a2.getComponentType());
1059            Class l4 = Class.forName("[[[[[J");
1060            assertSame(long[][][][][].class, l4);
1061
1062            try{
1063                System.out.println(Class.forName("[;"));
1064                fail("1");
1065            } catch (ClassNotFoundException ok) {}
1066            try{
1067                System.out.println(Class.forName("[["));
1068                fail("2");
1069            } catch (ClassNotFoundException ok) {}
1070            try{
1071                System.out.println(Class.forName("[L"));
1072                fail("3");
1073            } catch (ClassNotFoundException ok) {}
1074            try{
1075                System.out.println(Class.forName("[L;"));
1076                fail("4");
1077            } catch (ClassNotFoundException ok) {}
1078            try{
1079                System.out.println(Class.forName(";"));
1080                fail("5");
1081            } catch (ClassNotFoundException ok) {}
1082            try{
1083                System.out.println(Class.forName(""));
1084                fail("6");
1085            } catch (ClassNotFoundException ok) {}
1086        }
1087}
1088