SystemTest.java revision 3b5fe2883109da9470a8baf20e6700aba0d78193
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.AndroidOnly;
21import dalvik.annotation.TestTargets;
22import dalvik.annotation.TestLevel;
23import dalvik.annotation.TestTargetNew;
24import dalvik.annotation.TestTargetClass;
25
26import java.io.ByteArrayInputStream;
27import java.io.ByteArrayOutputStream;
28import java.io.IOException;
29import java.io.InputStream;
30import java.io.PrintStream;
31import java.nio.channels.Channel;
32import java.nio.channels.spi.SelectorProvider;
33import java.security.Permission;
34import java.util.Map;
35import java.util.Properties;
36import java.util.Vector;
37
38@TestTargetClass(System.class)
39public class SystemTest extends junit.framework.TestCase {
40
41    static boolean flag = false;
42
43    static boolean ranFinalize = false;
44
45    /**
46     * @tests java.lang.System#setIn(java.io.InputStream)
47     */
48    @TestTargetNew(
49        level = TestLevel.COMPLETE,
50        notes = "",
51        method = "setIn",
52        args = {java.io.InputStream.class}
53    )
54    public void test_setInLjava_io_InputStream() {
55        InputStream orgIn = System.in;
56        InputStream in = new ByteArrayInputStream(new byte[0]);
57        System.setIn(in);
58        assertTrue("in not set", System.in == in);
59        System.setIn(orgIn);
60
61        SecurityManager sm = new SecurityManager() {
62
63            public void checkPermission(Permission perm) {
64                if(perm.getName().equals("setIO")) {
65                    throw new SecurityException();
66                }
67            }
68        };
69
70        SecurityManager oldSm = System.getSecurityManager();
71        System.setSecurityManager(sm);
72
73        try {
74            System.setIn(in);
75            fail("SecurityException should be thrown.");
76        } catch (SecurityException e) {
77            // expected
78        } finally {
79            System.setSecurityManager(oldSm);
80        }
81    }
82
83    /**
84     * @tests java.lang.System#setOut(java.io.PrintStream)
85     */
86    @TestTargetNew(
87        level = TestLevel.COMPLETE,
88        notes = "",
89        method = "setOut",
90        args = {java.io.PrintStream.class}
91    )
92    public void test_setOutLjava_io_PrintStream() {
93        PrintStream orgOut = System.out;
94        PrintStream out = new PrintStream(new ByteArrayOutputStream());
95        System.setOut(out);
96        assertTrue("out not set", System.out == out);
97        System.setOut(orgOut);
98
99        SecurityManager sm = new SecurityManager() {
100
101            public void checkPermission(Permission perm) {
102                if(perm.getName().equals("setIO")) {
103                    throw new SecurityException();
104                }
105            }
106        };
107
108        SecurityManager oldSm = System.getSecurityManager();
109        System.setSecurityManager(sm);
110
111        try {
112            System.setOut(out);
113            fail("SecurityException should be thrown.");
114        } catch (SecurityException e) {
115            // expected
116        } finally {
117            System.setSecurityManager(oldSm);
118        }
119    }
120
121    /**
122     * @tests java.lang.System#setErr(java.io.PrintStream)
123     */
124    @TestTargetNew(
125        level = TestLevel.COMPLETE,
126        notes = "",
127        method = "setErr",
128        args = {java.io.PrintStream.class}
129    )
130    public void test_setErrLjava_io_PrintStream() {
131        PrintStream orgErr = System.err;
132        PrintStream err = new PrintStream(new ByteArrayOutputStream());
133        System.setErr(err);
134        assertTrue("err not set", System.err == err);
135        System.setErr(orgErr);
136
137        SecurityManager sm = new SecurityManager() {
138
139            public void checkPermission(Permission perm) {
140                if(perm.getName().equals("setIO")) {
141                    throw new SecurityException();
142                }
143            }
144        };
145
146        SecurityManager oldSm = System.getSecurityManager();
147        System.setSecurityManager(sm);
148
149        try {
150            System.setErr(err);
151            fail("SecurityException should be thrown.");
152        } catch (SecurityException e) {
153            // expected
154        } finally {
155            System.setSecurityManager(oldSm);
156        }
157    }
158
159    /**
160     * @tests java.lang.System#arraycopy(java.lang.Object, int,
161     *        java.lang.Object, int, int)
162     */
163    @TestTargetNew(
164        level = TestLevel.COMPLETE,
165        notes = "",
166        method = "arraycopy",
167        args = {java.lang.Object.class, int.class, java.lang.Object.class,
168                int.class, int.class}
169    )
170    public void test_arraycopyLjava_lang_ObjectILjava_lang_ObjectII() {
171        // Test for method void java.lang.System.arraycopy(java.lang.Object,
172        // int, java.lang.Object, int, int)
173        Integer a[] = new Integer[20];
174        Integer b[] = new Integer[20];
175        int i = 0;
176        while (i < a.length) {
177            a[i] = new Integer(i);
178            ++i;
179        }
180        System.arraycopy(a, 0, b, 0, a.length);
181        for (i = 0; i < a.length; i++)
182            assertTrue("Copied elements incorrectly", a[i].equals(b[i]));
183
184        /* Non primitive array types don't need to be identical */
185        String[] source1 = new String[] { "element1" };
186        Object[] dest1 = new Object[1];
187        System.arraycopy(source1, 0, dest1, 0, dest1.length);
188        assertTrue("Invalid copy 1", dest1[0] == source1[0]);
189
190        char[][] source = new char[][] { { 'H', 'e', 'l', 'l', 'o' },
191                { 'W', 'o', 'r', 'l', 'd' } };
192        char[][] dest = new char[2][];
193        System.arraycopy(source, 0, dest, 0, dest.length);
194        assertTrue("Invalid copy 2", dest[0] == source[0]
195                && dest[1] == source[1]);
196
197        try {
198            // copy from non array object into Object array
199            System.arraycopy(new Object(), 0, b, 0, 0);
200            fail("ArrayStoreException is not thrown.");
201        } catch(ArrayStoreException  ase) {
202            //expected
203        }
204
205        try {
206            // copy from Object array into non array object
207            System.arraycopy(a, 0, new Object(), 0, 0);
208            fail("ArrayStoreException is not thrown.");
209        } catch(ArrayStoreException  ase) {
210            //expected
211        }
212
213        try {
214            // copy from primitive array into object array
215            System.arraycopy(new char[] {'a'}, 0, new String[1], 0, 1);
216            fail("ArrayStoreException is not thrown.");
217        } catch(ArrayStoreException  ase) {
218            //expected
219        }
220
221        try {
222            // copy from object array into primitive array
223            System.arraycopy(new String[] {"a"}, 0, new char[1], 0, 1);
224            fail("ArrayStoreException is not thrown.");
225        } catch(ArrayStoreException  ase) {
226            //expected
227        }
228
229        try {
230            // copy from primitive array into an array of another primitive type
231            System.arraycopy(new char[] {'a'}, 0, new int[1], 0, 1);
232            fail("ArrayStoreException is not thrown.");
233        } catch(ArrayStoreException  ase) {
234            //expected
235        }
236
237        try {
238            // copy from object array into an array of another Object type
239            System.arraycopy(new Character[] {'a'}, 0, new Integer[1], 0, 1);
240            fail("ArrayStoreException is not thrown.");
241        } catch(ArrayStoreException  ase) {
242            //expected
243        }
244
245        try {
246            // copy from null into an array of a primitive type
247            System.arraycopy(null, 0, new int[1], 0, 1);
248            fail("NullPointerException is not thrown.");
249        } catch(NullPointerException npe) {
250            //expected
251        }
252
253        try {
254            // copy from a primitive array into null
255            System.arraycopy(new int[]{'1'}, 0, null, 0, 1);
256            fail("NullPointerException is not thrown.");
257        } catch(NullPointerException npe) {
258            //expected
259        }
260
261        try {
262            System.arraycopy(a, a.length + 1, b, 0, 1);
263            fail("IndexOutOfBoundsException is not thrown.");
264        } catch(IndexOutOfBoundsException ioobe) {
265            //expected
266        }
267
268        try {
269            System.arraycopy(a, -1, b, 0, 1);
270            fail("IndexOutOfBoundsException is not thrown.");
271        } catch(IndexOutOfBoundsException ioobe) {
272            //expected
273        }
274
275        try {
276            System.arraycopy(a, 0, b, -1, 1);
277            fail("IndexOutOfBoundsException is not thrown.");
278        } catch(IndexOutOfBoundsException ioobe) {
279            //expected
280        }
281
282        try {
283            System.arraycopy(a, 0, b, 0, -1);
284            fail("IndexOutOfBoundsException is not thrown.");
285        } catch(IndexOutOfBoundsException ioobe) {
286            //expected
287        }
288
289        try {
290            System.arraycopy(a, 11, b, 0, 10);
291            fail("IndexOutOfBoundsException is not thrown.");
292        } catch(IndexOutOfBoundsException ioobe) {
293            //expected
294        }
295
296        try {
297            System.arraycopy(a, Integer.MAX_VALUE, b, 0, 10);
298            fail("IndexOutOfBoundsException is not thrown.");
299        } catch(IndexOutOfBoundsException ioobe) {
300            //expected
301        }
302
303        try {
304            System.arraycopy(a, 0, b, Integer.MAX_VALUE, 10);
305            fail("IndexOutOfBoundsException is not thrown.");
306        } catch(IndexOutOfBoundsException ioobe) {
307            //expected
308        }
309
310        try {
311            System.arraycopy(a, 0, b, 10, Integer.MAX_VALUE);
312            fail("IndexOutOfBoundsException is not thrown.");
313        } catch(IndexOutOfBoundsException ioobe) {
314            //expected
315        }
316    }
317
318    /**
319     * @tests java.lang.System#currentTimeMillis()
320     */
321    @TestTargetNew(
322        level = TestLevel.COMPLETE,
323        notes = "",
324        method = "currentTimeMillis",
325        args = {}
326    )
327    public void test_currentTimeMillis() {
328        // Test for method long java.lang.System.currentTimeMillis()
329        try {
330            long firstRead = System.currentTimeMillis();
331            try {
332                Thread.sleep(150);
333            } catch (InterruptedException e) {
334            }
335            long secondRead = System.currentTimeMillis();
336            assertTrue("Incorrect times returned: " + firstRead + ", "
337                    + secondRead, firstRead < secondRead);
338        } catch (Exception e) {
339            fail("Exception during test: " + e.toString());
340        }
341    }
342
343    /**
344     * @tests java.lang.System#exit(int)
345     */
346    @TestTargetNew(
347        level = TestLevel.COMPLETE,
348        notes = "Verifies SecurityException.",
349        method = "exit",
350        args = {int.class}
351    )
352    public void test_exitI() {
353        SecurityManager sm = new SecurityManager() {
354
355            final String forbidenPermissionName = "user.dir";
356
357            public void checkPermission(Permission perm) {
358                if (perm.getName().equals(forbidenPermissionName)) {
359                    throw new SecurityException();
360                }
361            }
362
363            public void checkExit(int status) {
364                if(status == -1)
365                    throw new SecurityException();
366            }
367
368        };
369
370        SecurityManager oldSm = System.getSecurityManager();
371        System.setSecurityManager(sm);
372        try {
373            System.exit(-1);
374            fail("Should throw SecurityException");
375        } catch (SecurityException e) {
376            // expected
377        } finally {
378            System.setSecurityManager(oldSm);
379        }
380    }
381
382    /**
383     * @tests java.lang.System#getProperties()
384     */
385    @TestTargetNew(
386        level = TestLevel.COMPLETE,
387        notes = "",
388        method = "getProperties",
389        args = {}
390    )
391    public void test_getProperties() {
392
393       // Test for method java.util.Properties java.lang.System.getProperties()
394       /* String[] props = { "java.version", "java.vendor", "java.vendor.url",
395                "java.home", "java.vm.specification.version",
396                "java.vm.specification.vendor", "java.vm.specification.name",
397                "java.vm.version", "java.vm.vendor", "java.vm.name",
398                "java.specification.name", "java.specification.vendor",
399                "java.specification.name", "java.class.version",
400                "java.class.path", "java.ext.dirs", "os.name", "os.arch",
401                "os.version", "file.separator", "path.separator",
402                "line.separator", "user.name", "user.home", "user.dir", };
403        */
404
405        String [] props = {"java.vendor.url",
406                "java.class.path", "user.home",
407                "java.class.version", "os.version",
408                "java.vendor", "user.dir",
409                /*"user.timezone",*/ "path.separator",
410                "os.name", "os.arch",
411                "line.separator", "file.separator",
412                "user.name", "java.version", "java.home" };
413
414        /* Available properties.
415        String [] props = {"java.boot.class.path", "java.class.path",
416                "java.class.version", "java.compiler", "java.ext.dirs",
417                "java.home", "java.io.tmpdir", "java.library.path",
418                "java.vendor", "java.vendor.url", "java.version",
419                "java.vm.name", "java.vm.specification.name",
420                "java.vm.specification.vendor", "java.vm.specification.version",
421                "java.vm.vendor", "java.vm.version", "java.specification.name",
422                "java.specification.vendor", "java.specification.version",
423                "os.arch", "os.name", "os.version", "user.home", "user.name",
424                "user.dir", "file.separator", "line.separator",
425                "path.separator", "java.runtime.name", "java.runtime.version",
426                "java.vm.vendor.url", "file.encoding","user.language",
427                "user.region"};
428        */
429
430        Properties p = System.getProperties();
431        assertTrue(p.size() > 0);
432
433        // Ensure spec'ed properties are non-null. See System.getProperties()
434        // spec.
435
436        for (int i = 0; i < props.length; i++) {
437            assertNotNull("There is no property among returned properties: "
438                    + props[i], p.getProperty(props[i]));
439            assertNotNull("System property is null: " + props[i],
440                    System.getProperty(props[i]));
441        }
442
443        SecurityManager sm = new SecurityManager() {
444
445            public void checkPermission(Permission perm) {
446            }
447
448            public void checkPropertiesAccess() {
449                throw new SecurityException();
450            }
451        };
452
453        SecurityManager oldSm = System.getSecurityManager();
454        System.setSecurityManager(sm);
455
456        try {
457            System.getProperties();
458            fail("SecurityException should be thrown.");
459        } catch (SecurityException e) {
460            // expected
461        } finally {
462            System.setSecurityManager(oldSm);
463        }
464    }
465
466    /**
467     * @tests java.lang.System#getProperty(java.lang.String)
468     */
469    @TestTargetNew(
470        level = TestLevel.COMPLETE,
471        notes = "",
472        method = "getProperty",
473        args = {java.lang.String.class}
474    )
475    public void test_getPropertyLjava_lang_String() {
476        // Test for method java.lang.String
477        // java.lang.System.getProperty(java.lang.String)
478        assertTrue("Failed to return correct property value", System
479                .getProperty("line.separator").indexOf("\n", 0) >= 0);
480
481        boolean is8859_1 = true;
482        String encoding = System.getProperty("file.encoding");
483        byte[] bytes = new byte[128];
484        char[] chars = new char[128];
485        for (int i = 0; i < bytes.length; i++) {
486            bytes[i] = (byte) (i + 128);
487            chars[i] = (char) (i + 128);
488        }
489        String charResult = new String(bytes);
490        byte[] byteResult = new String(chars).getBytes();
491        if (charResult.length() == 128 && byteResult.length == 128) {
492            for (int i = 0; i < bytes.length; i++) {
493                if (charResult.charAt(i) != (char) (i + 128)
494                        || byteResult[i] != (byte) (i + 128))
495                    is8859_1 = false;
496            }
497        } else
498            is8859_1 = false;
499        String[] possibles = new String[] { "ISO8859_1", "8859_1", "ISO8859-1",
500                "ISO-8859-1", "ISO_8859-1", "ISO_8859-1:1978", "ISO-IR-100",
501                "LATIN1", "CSISOLATIN1" };
502        boolean found8859_1 = false;
503        for (int i = 0; i < possibles.length; i++) {
504            if (possibles[i].equals(encoding)) {
505                found8859_1 = true;
506                break;
507            }
508        }
509        assertTrue("Wrong encoding: " + encoding, !is8859_1 || found8859_1);
510
511        try {
512            System.getProperty(null);
513            fail("NullPointerException should be thrown.");
514        } catch(NullPointerException npe) {
515            //expected
516        }
517
518        try {
519            System.getProperty("");
520            fail("IllegalArgumentException should be thrown.");
521        } catch(IllegalArgumentException  iae) {
522            //expected
523        }
524
525        SecurityManager sm = new SecurityManager() {
526
527            public void checkPermission(Permission perm) {
528            }
529
530            @SuppressWarnings("unused")
531            public void checkPropertyAccess(String key) {
532                throw new SecurityException();
533            }
534        };
535
536        SecurityManager oldSm = System.getSecurityManager();
537        System.setSecurityManager(sm);
538
539        try {
540            System.getProperty("user.name");
541            fail("SecurityException should be thrown.");
542        } catch (SecurityException e) {
543            // expected
544        } finally {
545            System.setSecurityManager(oldSm);
546        }
547    }
548
549    /**
550     * @tests java.lang.System#getProperty(java.lang.String, java.lang.String)
551     */
552    @TestTargetNew(
553        level = TestLevel.COMPLETE,
554        notes = "",
555        method = "getProperty",
556        args = {java.lang.String.class, java.lang.String.class}
557    )
558    public void test_getPropertyLjava_lang_StringLjava_lang_String() {
559        // Test for method java.lang.String
560        // java.lang.System.getProperty(java.lang.String, java.lang.String)
561        assertTrue("Failed to return correct property value: "
562                + System.getProperty("line.separator", "99999"), System
563                .getProperty("line.separator", "99999").indexOf("\n", 0) >= 0);
564        assertEquals("Failed to return correct property value", "bogus", System
565                .getProperty("bogus.prop", "bogus"));
566
567        try {
568            System.getProperty(null, "0.0");
569            fail("NullPointerException should be thrown.");
570        } catch(NullPointerException npe) {
571            //expected
572        }
573
574        try {
575            System.getProperty("", "0");
576            fail("IllegalArgumentException should be thrown.");
577        } catch(IllegalArgumentException  iae) {
578            //expected
579        }
580
581        SecurityManager sm = new SecurityManager() {
582
583            public void checkPermission(Permission perm) {
584            }
585
586            @SuppressWarnings("unused")
587            public void checkPropertyAccess(String key) {
588                throw new SecurityException();
589            }
590        };
591
592        SecurityManager oldSm = System.getSecurityManager();
593        System.setSecurityManager(sm);
594
595        try {
596            System.getProperty("java.version", "0");
597            fail("SecurityException should be thrown.");
598        } catch (SecurityException e) {
599            // expected
600        } finally {
601            System.setSecurityManager(oldSm);
602        }
603    }
604
605    /**
606     * @tests java.lang.System#setProperty(java.lang.String, java.lang.String)
607     */
608    @TestTargetNew(
609        level = TestLevel.COMPLETE,
610        notes = "",
611        method = "setProperty",
612        args = {java.lang.String.class, java.lang.String.class}
613    )
614    public void test_setPropertyLjava_lang_StringLjava_lang_String() {
615        // Test for method java.lang.String
616        // java.lang.System.setProperty(java.lang.String, java.lang.String)
617
618        assertNull("Failed to return null", System.setProperty("testing",
619                "value1"));
620        assertTrue("Failed to return old value", System.setProperty("testing",
621                "value2") == "value1");
622        assertTrue("Failed to find value",
623                System.getProperty("testing") == "value2");
624
625        boolean exception = false;
626        try {
627            System.setProperty("", "default");
628        } catch (IllegalArgumentException e) {
629            exception = true;
630        }
631        assertTrue("Expected IllegalArgumentException", exception);
632    }
633
634    /**
635     * @tests java.lang.System#getSecurityManager()
636     */
637    @TestTargetNew(
638        level = TestLevel.PARTIAL,
639        notes = "Doesn't check positive functionality.",
640        method = "getSecurityManager",
641        args = {}
642    )
643    public void test_getSecurityManager() {
644        // Test for method java.lang.SecurityManager
645        // java.lang.System.getSecurityManager()
646        assertNull("Returned incorrect SecurityManager", System
647                .getSecurityManager());
648    }
649
650    /**
651     * @tests java.lang.System#identityHashCode(java.lang.Object)
652     */
653    @TestTargetNew(
654        level = TestLevel.COMPLETE,
655        notes = "",
656        method = "identityHashCode",
657        args = {java.lang.Object.class}
658    )
659    public void test_identityHashCodeLjava_lang_Object() {
660        // Test for method int
661        // java.lang.System.identityHashCode(java.lang.Object)
662        Object o = new Object();
663        String s = "Gabba";
664        assertEquals("Nonzero returned for null",
665                0, System.identityHashCode(null));
666        assertTrue("Nonequal has returned for Object", System
667                .identityHashCode(o) == o.hashCode());
668        assertTrue("Same as usual hash returned for String", System
669                .identityHashCode(s) != s.hashCode());
670    }
671
672    /**
673     * @throws IOException
674     * @tests java.lang.System#inheritedChannel()
675     */
676    @TestTargetNew(
677        level = TestLevel.COMPLETE,
678        notes = "",
679        method = "inheritedChannel",
680        args = {}
681    )
682    public void test_inheritedChannel() throws IOException {
683        Channel iChannel = System.inheritedChannel();
684        assertNull("Incorrect value of channel", iChannel);
685        SelectorProvider sp = SelectorProvider.provider();
686        assertEquals("Incorrect value of channel",
687                sp.inheritedChannel(), iChannel);
688
689        SecurityManager sm = new SecurityManager() {
690
691            public void checkPermission(Permission perm) {
692                if(perm.getName().equals("inheritedChannel")) {
693                    throw new SecurityException();
694                }
695            }
696        };
697
698        SecurityManager oldSm = System.getSecurityManager();
699        System.setSecurityManager(sm);
700
701        try {
702            System.inheritedChannel();
703            fail("SecurityException should be thrown.");
704        } catch (SecurityException e) {
705            // expected
706        } finally {
707            System.setSecurityManager(oldSm);
708        }
709    }
710
711    /**
712     * @tests java.lang.System#runFinalization()
713     */
714    @TestTargetNew(
715        level = TestLevel.COMPLETE,
716        notes = "",
717        method = "runFinalization",
718        args = {}
719    )
720    public void test_runFinalization() {
721        // Test for method void java.lang.System.runFinalization()
722
723        flag = true;
724        createInstance();
725        int count = 10;
726        // the gc below likely bogosifies the test, but will have to do for
727        // the moment
728        while (!ranFinalize && count-- > 0) {
729            System.gc();
730            System.runFinalization();
731        }
732        assertTrue("Failed to run finalization", ranFinalize);
733    }
734
735    /**
736     * @tests java.lang.System#runFinalizersOnExit(boolean)
737     */
738    @TestTargetNew(
739        level = TestLevel.COMPLETE,
740        notes = "",
741        method = "runFinalizersOnExit",
742        args = {boolean.class}
743    )
744    @SuppressWarnings("deprecation")
745    public void test_runFinalizersOnExitZ() {
746        // Can we call the method at least?
747        try {
748            System.runFinalizersOnExit(false);
749        } catch (Throwable t) {
750            fail("Failed to set runFinalizersOnExit");
751        }
752
753        try {
754            System.runFinalizersOnExit(true);
755        } catch (Throwable t) {
756            fail("Failed to set runFinalizersOnExit");
757        }
758
759        SecurityManager sm = new SecurityManager() {
760
761            public void checkPermission(Permission perm) {
762            }
763
764            public void checkExit(int status) {
765                throw new SecurityException();
766            }
767        };
768
769        SecurityManager oldSm = System.getSecurityManager();
770        System.setSecurityManager(sm);
771
772        try {
773            System.runFinalizersOnExit(true);
774            fail("SecurityException should be thrown.");
775        } catch (SecurityException e) {
776            // expected
777        } finally {
778            System.setSecurityManager(oldSm);
779        }
780    }
781
782    /**
783     * @tests java.lang.System#setProperties(java.util.Properties)
784     */
785    @TestTargetNew(
786        level = TestLevel.COMPLETE,
787        notes = "",
788        method = "setProperties",
789        args = {java.util.Properties.class}
790    )
791    public void test_setPropertiesLjava_util_Properties() {
792        // Test for method void
793        // java.lang.System.setProperties(java.util.Properties)
794
795        Properties orgProps = System.getProperties();
796        java.util.Properties tProps = new java.util.Properties();
797        tProps.put("test.prop", "this is a test property");
798        tProps.put("bogus.prop", "bogus");
799        System.setProperties(tProps);
800        try {
801            assertEquals("Failed to set properties", "this is a test property", System.getProperties()
802                    .getProperty("test.prop"));
803        } finally {
804            // restore the original properties
805            System.setProperties(orgProps);
806        }
807    }
808
809    //Regression Test for Harmony-2356
810    @TestTargetNew(
811        level = TestLevel.COMPLETE,
812        notes = "",
813        method = "getenv",
814        args = {}
815    )
816    public void testEnvUnmodifiable() {
817        Map map = System.getenv();
818        try {
819            map.containsKey(null);
820            fail("Should throw NullPointerExcepiton.");
821        } catch (NullPointerException e) {
822            // expected
823        }
824
825        try {
826            map.containsKey(new Integer(10));
827            fail("Should throw ClassCastException.");
828        } catch (ClassCastException e) {
829            // expected
830        }
831
832        try {
833            map.containsValue(null);
834            fail("Should throw NullPointerExcepiton.");
835        } catch (NullPointerException e) {
836            // expected
837        }
838
839        try {
840            map.containsValue(new Integer(10));
841            fail("Should throw ClassCastException.");
842        } catch (ClassCastException e) {
843            // expected
844        }
845
846        try {
847            map.get(null);
848            fail("Should throw NullPointerExcepiton.");
849        } catch (NullPointerException e) {
850            // expected
851        }
852
853        try {
854            map.get(new Integer(10));
855            fail("Should throw ClassCastException.");
856        } catch (ClassCastException e) {
857            // expected
858        }
859
860        try {
861            map.put(null, "AAA");
862            fail("Should throw UnsupportedOperationExcepiton.");
863        } catch (UnsupportedOperationException e) {
864            // expected
865        }
866
867        try {
868            map.put("AAA", new Integer(10));
869            fail("Should throw UnsupportedOperationException.");
870        } catch (UnsupportedOperationException e) {
871            // expected
872        }
873
874        try {
875            map.put("AAA", "BBB");
876            fail("Should throw UnsupportedOperationException.");
877        } catch (UnsupportedOperationException e) {
878            // expected
879        }
880
881        try {
882            map.clear();
883            fail("Should throw UnsupportedOperationException.");
884        } catch (UnsupportedOperationException e) {
885            // expected
886        }
887
888        try {
889            map.remove(null);
890            fail("Should throw UnsupportedOperationException.");
891        } catch (UnsupportedOperationException e) {
892            // expected
893        }
894
895    }
896    @TestTargets({
897        @TestTargetNew(
898            level = TestLevel.COMPLETE,
899            notes = "",
900            method = "setSecurityManager",
901            args = {java.lang.SecurityManager.class}
902        ),
903        @TestTargetNew(
904            level = TestLevel.COMPLETE,
905            notes = "",
906            method = "getSecurityManager",
907            args = {}
908        )
909    })
910    public void test_setSecurityManagerLjava_lang_SecurityManager() {
911        assertEquals("Incorrect SecurityManager",
912                null, System.getSecurityManager());
913        try {
914            SecurityManager localManager = new MockSecurityManager();
915            System.setSecurityManager(localManager);
916            assertEquals("Incorrect SecurityManager",
917                    localManager, System.getSecurityManager());
918        } finally {
919            System.setSecurityManager(null);
920        }
921    }
922
923    @TestTargetNew(
924        level = TestLevel.COMPLETE,
925        notes = "",
926        method = "clearProperty",
927        args = {java.lang.String.class}
928    )
929    public void test_clearProperty() {
930        System.setProperty("test", "value");
931        System.clearProperty("test");
932        assertNull("Property was not deleted.", System.getProperty("test"));
933
934        try {
935            System.clearProperty(null);
936            fail("NullPointerException is not thrown.");
937        } catch(NullPointerException npe) {
938            //expected
939        }
940
941        try {
942            System.clearProperty("");
943            fail("IllegalArgumentException is not thrown.");
944        } catch(IllegalArgumentException iae) {
945            //expected
946        }
947
948        SecurityManager sm = new SecurityManager() {
949
950            public void checkPermission(Permission perm) {
951                if (perm.getName().equals("test")) {
952                    throw new SecurityException();
953                }
954            }
955        };
956
957        SecurityManager oldSm = System.getSecurityManager();
958        System.setSecurityManager(sm);
959        try {
960            System.clearProperty("test");
961            fail("SecurityException should be thrown.");
962        } catch (SecurityException e) {
963            // expected
964        } finally {
965            System.setSecurityManager(oldSm);
966        }
967    }
968
969    @TestTargetNew(
970        level = TestLevel.COMPLETE,
971        notes = "",
972        method = "gc",
973        args = {}
974    )
975    public void test_gc() {
976        Runtime rt =  Runtime.getRuntime();
977        Vector<StringBuffer> vec = new Vector<StringBuffer>();
978        long beforeTest = rt.freeMemory();
979        while(rt.freeMemory() < beforeTest * 2/3) {
980             vec.add(new StringBuffer(1000));
981        }
982        vec = null;
983        long beforeGC = rt.freeMemory();
984        System.gc();
985        long afterGC = rt.freeMemory();
986        assertTrue("memory was not released after calling System.gc()." +
987                "before gc: " + beforeGC + "; after gc: " + afterGC,
988                beforeGC < afterGC);
989    }
990
991    @TestTargetNew(
992        level = TestLevel.COMPLETE,
993        notes = "",
994        method = "getenv",
995        args = {}
996    )
997    public void test_getenv() {
998
999        // String[] props = { "PATH", "HOME", "USER"};
1000        // only PATH of these three exists on android
1001        String[] props = { "PATH" };
1002
1003        Map<String,String> envMap = System.getenv();
1004        assertFalse("environment map is empty.", envMap.isEmpty());
1005        assertTrue("env map contains less than 3 keys.",
1006                props.length < envMap.keySet().size());
1007        for(int i = 0; i < props.length; i++) {
1008           assertNotNull("There is no property: " + props[i],
1009                   envMap.get(props[i]));
1010        }
1011
1012        SecurityManager sm = new SecurityManager() {
1013
1014            public void checkPermission(Permission perm) {
1015                if(perm.getName().equals("getenv.*")) {
1016                    throw new SecurityException();
1017                }
1018            }
1019        };
1020
1021        SecurityManager oldSm = System.getSecurityManager();
1022        System.setSecurityManager(sm);
1023
1024        try {
1025            System.getenv();
1026            fail("SecurityException should be thrown.");
1027        } catch (SecurityException e) {
1028            // expected
1029        } finally {
1030            System.setSecurityManager(oldSm);
1031        }
1032    }
1033
1034    @TestTargetNew(
1035        level = TestLevel.COMPLETE,
1036        notes = "",
1037        method = "getenv",
1038        args = {java.lang.String.class}
1039    )
1040    public void test_getenvLString() {
1041
1042        assertNotNull("PATH environment variable is not found",
1043                  System.getenv("PATH"));
1044
1045        assertNull("Doesn't return NULL for non existent property",
1046                  System.getenv("nonexistent.property"));
1047
1048        SecurityManager sm = new SecurityManager() {
1049
1050            public void checkPermission(Permission perm) {
1051                if(perm.getName().equals("getenv.PATH")) {
1052                    throw new SecurityException();
1053                }
1054            }
1055        };
1056
1057        SecurityManager oldSm = System.getSecurityManager();
1058        System.setSecurityManager(sm);
1059
1060        try {
1061            System.getenv("PATH");
1062            fail("SecurityException should be thrown.");
1063        } catch (SecurityException e) {
1064            // expected
1065        } finally {
1066            System.setSecurityManager(oldSm);
1067        }
1068
1069        try {
1070            System.getenv(null);
1071            fail("NullPointerException is not thrown.");
1072        } catch(NullPointerException npe) {
1073            //expected
1074        }
1075    }
1076
1077    @TestTargetNew(
1078        level = TestLevel.COMPLETE,
1079        notes = "",
1080        method = "load",
1081        args = {java.lang.String.class}
1082    )
1083    @AndroidOnly("No x86 version of this library")
1084    public void test_load() {
1085        try {
1086            new TestLibrary().checkString();
1087            fail("UnsatisfiedLinkError was not thrown.");
1088        } catch(UnsatisfiedLinkError  e) {
1089            //expected
1090        }
1091
1092        try {
1093            System.load("nonExistentLibrary");
1094            fail("UnsatisfiedLinkError was not thrown.");
1095        } catch(UnsatisfiedLinkError ule) {
1096            //expected
1097        }
1098
1099        try {
1100            System.load(null);
1101            fail("NullPointerException was not thrown.");
1102        } catch(NullPointerException npe) {
1103            //expected
1104        }
1105
1106        SecurityManager sm = new SecurityManager() {
1107
1108            public void checkPermission(Permission perm) {
1109
1110            }
1111
1112            public void checkLink(String lib) {
1113                throw new SecurityException();
1114            }
1115        };
1116
1117        SecurityManager oldSm = System.getSecurityManager();
1118        System.setSecurityManager(sm);
1119        try {
1120            System.load("libTestLibrary.so");
1121            fail("SecurityException should be thrown.");
1122        } catch (SecurityException e) {
1123            // expected
1124        } finally {
1125            System.setSecurityManager(oldSm);
1126        }
1127    }
1128
1129    @TestTargetNew(
1130        level = TestLevel.COMPLETE,
1131        notes = "",
1132        method = "loadLibrary",
1133        args = {java.lang.String.class}
1134    )
1135    public void test_loadLibrary() {
1136
1137        try {
1138            System.loadLibrary("nonExistentLibrary");
1139            fail("UnsatisfiedLinkError was not thrown.");
1140        } catch(UnsatisfiedLinkError ule) {
1141            //expected
1142        }
1143
1144        try {
1145            System.loadLibrary(null);
1146            fail("NullPointerException was not thrown.");
1147        } catch(NullPointerException npe) {
1148            //expected
1149        }
1150
1151        SecurityManager sm = new SecurityManager() {
1152
1153            public void checkPermission(Permission perm) {
1154            }
1155
1156            public void checkLink(String lib) {
1157                throw new SecurityException();
1158            }
1159         };
1160
1161         SecurityManager oldSm = System.getSecurityManager();
1162         System.setSecurityManager(sm);
1163         try {
1164             System.loadLibrary("libTestLibrary.so");
1165             fail("SecurityException should be thrown.");
1166         } catch (SecurityException e) {
1167             // expected
1168         } finally {
1169             System.setSecurityManager(oldSm);
1170         }
1171    }
1172
1173    @TestTargetNew(
1174        level = TestLevel.COMPLETE,
1175        notes = "",
1176        method = "mapLibraryName",
1177        args = {java.lang.String.class}
1178    )
1179    public void test_mapLibraryName() {
1180        assertEquals("libname.so", System.mapLibraryName("name"));
1181
1182        try {
1183            System.mapLibraryName(null);
1184            fail("NullPointerException is not thrown.");
1185        } catch(NullPointerException npe) {
1186            //expected
1187        }
1188    }
1189
1190    @TestTargetNew(
1191        level = TestLevel.COMPLETE,
1192        notes = "",
1193        method = "nanoTime",
1194        args = {}
1195    )
1196    public void test_nanoTime() {
1197        long sleepTime = 5000;
1198        long beginTime = System.nanoTime();
1199        try {
1200            Thread.sleep(sleepTime);
1201        } catch(Exception e) {
1202            fail("Unknown exception was thrown.");
1203        }
1204        long endTime = System.nanoTime();
1205        assertTrue((endTime - beginTime) > sleepTime * 1000000);
1206    }
1207
1208    @Override
1209    protected void setUp() {
1210        flag = false;
1211        ranFinalize = false;
1212    }
1213
1214    protected SystemTest createInstance() {
1215        return new SystemTest("FT");
1216    }
1217
1218    @Override
1219    protected void finalize() {
1220        if (flag)
1221            ranFinalize = true;
1222    }
1223
1224    public SystemTest() {
1225    }
1226
1227    public SystemTest(String name) {
1228        super(name);
1229    }
1230
1231    private class MockSecurityManager extends SecurityManager {
1232        @Override
1233        public void checkPermission(Permission perm) {
1234            if (perm.equals(new RuntimePermission("inheritedChannel")))
1235                throw new SecurityException("Incorrect permission");
1236        }
1237    }
1238}
1239