Home | History | Annotate | Download | only in io
      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 
     18 package org.apache.harmony.tests.java.io;
     19 
     20 import java.io.ByteArrayInputStream;
     21 import java.io.ByteArrayOutputStream;
     22 import java.io.FilterOutputStream;
     23 import java.io.InputStreamReader;
     24 import java.io.DataInputStream;
     25 import java.io.File;
     26 import java.io.FileNotFoundException;
     27 import java.io.IOException;
     28 import java.io.OutputStream;
     29 import java.io.PrintStream;
     30 import java.io.UnsupportedEncodingException;
     31 import java.nio.charset.Charset;
     32 import java.nio.charset.StandardCharsets;
     33 import java.util.Arrays;
     34 import java.util.Base64;
     35 import java.util.Locale;
     36 import libcore.io.IoUtils;
     37 
     38 public class PrintStreamTest extends junit.framework.TestCase {
     39     private static final String UNICODE_STRING =
     40             "K\u03B1\u03BB\u03B7\u00B5\u03B5\u00B4\u03C1\u03B1 \u03BA\u03BF\u00B4\u03C3\u00B5\u03B5";
     41 
     42     ByteArrayOutputStream bos = new ByteArrayOutputStream();
     43 
     44     byte[] ibuf = new byte[4096];
     45 
     46     private File testFile = null;
     47 
     48     private String testFilePath = null;
     49 
     50     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_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_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";
     51 
     52     private static class MockPrintStream extends PrintStream {
     53 
     54         public MockPrintStream(String fileName) throws FileNotFoundException {
     55             super(fileName);
     56         }
     57 
     58         public MockPrintStream(String fileName, String csn) throws FileNotFoundException, UnsupportedEncodingException {
     59             super(fileName, csn);
     60         }
     61 
     62         public MockPrintStream(OutputStream os) {
     63             super(os);
     64         }
     65 
     66         @Override
     67         public void clearError() {
     68             super.clearError();
     69         }
     70 
     71         @Override
     72         public void setError() {
     73             super.setError();
     74         }
     75     }
     76 
     77     /**
     78      * {@link java.io.PrintStream#PrintStream(String)}
     79      */
     80     public void test_Constructor_Ljava_lang_String() throws IOException {
     81         PrintStream os = new PrintStream(testFilePath);
     82         os.print(UNICODE_STRING);
     83         os.close();
     84         assertFileContents(UNICODE_STRING.getBytes(Charset.defaultCharset()), testFile);
     85     }
     86 
     87     /**
     88      * {@link java.io.PrintStream#PrintStream(String, String)}
     89      */
     90     public void test_Constructor_Ljava_lang_String_Ljava_lang_String() throws Exception {
     91         // Test that a bogus charset is mentioned in the exception
     92         try {
     93             new PrintStream(testFilePath, "Bogus");
     94             fail("Exception expected");
     95         } catch (UnsupportedEncodingException e) {
     96             assertNotNull(e.getMessage());
     97         }
     98 
     99         {
    100             PrintStream os = new PrintStream(testFilePath, "utf-8");
    101             os.print(UNICODE_STRING);
    102             os.close();
    103             assertFileContents(UNICODE_STRING.getBytes(StandardCharsets.UTF_8), testFile);
    104         }
    105 
    106         {
    107             PrintStream os = new PrintStream(testFilePath, "utf-16");
    108             os.print(UNICODE_STRING);
    109             os.close();
    110             assertFileContents(UNICODE_STRING.getBytes(StandardCharsets.UTF_16), testFile);
    111         }
    112     }
    113 
    114     /**
    115      * java.io.PrintStream#PrintStream(java.io.OutputStream)
    116      */
    117     public void test_ConstructorLjava_io_OutputStream() throws Exception {
    118         // Test for method java.io.PrintStream(java.io.OutputStream)
    119         PrintStream os = new PrintStream(bos);
    120         os.print(2345.76834720202);
    121         os.close();
    122 
    123         // regression for HARMONY-1195
    124         try {
    125             os = new PrintStream(bos, true, null);
    126             fail("Should throw NPE");
    127         } catch (NullPointerException e) {
    128         }
    129     }
    130 
    131     /**
    132      * java.io.PrintStream#PrintStream(java.io.OutputStream, boolean)
    133      */
    134     public void test_ConstructorLjava_io_OutputStreamZ() {
    135         // Test for method java.io.PrintStream(java.io.OutputStream, boolean)
    136         PrintStream os = new PrintStream(bos);
    137         os.println(2345.76834720202);
    138         os.flush();
    139         assertTrue("Bytes not written", bos.size() > 0);
    140         os.close();
    141     }
    142 
    143     /**
    144      * java.io.PrintStream#PrintStream(java.io.OutputStream, boolean, String)
    145      */
    146     public void test_ConstructorLjava_io_OutputStreamZLjava_lang_String() throws Exception {
    147         try {
    148             new PrintStream(new ByteArrayOutputStream(), false,
    149                     "%Illegal_name!");
    150             fail("Expected UnsupportedEncodingException");
    151         } catch (UnsupportedEncodingException e) {
    152             // expected
    153         }
    154 
    155         {
    156             ByteArrayOutputStream bos = new ByteArrayOutputStream();
    157             PrintStream printStream = new PrintStream(bos, true /* autoFlush */, "utf-8");
    158             printStream.print(UNICODE_STRING);
    159             printStream.close();
    160             assertByteArraysEqual(UNICODE_STRING.getBytes(StandardCharsets.UTF_8),
    161                     bos.toByteArray());
    162         }
    163 
    164         {
    165             ByteArrayOutputStream bos = new ByteArrayOutputStream();
    166             PrintStream printStream = new PrintStream(bos, true /* autoFlush */, "utf-16");
    167             printStream.print(UNICODE_STRING);
    168             printStream.close();
    169             assertByteArraysEqual(UNICODE_STRING.getBytes(StandardCharsets.UTF_16),
    170                     bos.toByteArray());
    171         }
    172     }
    173 
    174     /**
    175      * java.io.PrintStream#checkError()
    176      */
    177     public void test_checkError() throws Exception {
    178         // Test for method boolean java.io.PrintStream.checkError()
    179         PrintStream os = new PrintStream(new OutputStream() {
    180 
    181             public void write(int b) throws IOException {
    182                 throw new IOException();
    183             }
    184 
    185             public void write(byte[] b, int o, int l) throws IOException {
    186                 throw new IOException();
    187             }
    188         });
    189         os.print(fileString.substring(0, 501));
    190 
    191         assertTrue("Checkerror should return true", os.checkError());
    192     }
    193 
    194     /**
    195      * {@link java.io.PrintStream#clearError()}
    196      */
    197     public void test_clearError() throws FileNotFoundException {
    198         MockPrintStream os = new MockPrintStream(testFilePath);
    199         assertFalse(os.checkError());
    200         os.setError();
    201         assertTrue(os.checkError());
    202         os.clearError();
    203         assertFalse(os.checkError());
    204         os.close();
    205     }
    206 
    207     /**
    208      * java.io.PrintStream#close()
    209      */
    210     public void test_close() throws Exception {
    211         // Test for method void java.io.PrintStream.close()
    212         PrintStream os = new PrintStream(bos);
    213         os.close();
    214         bos.close();
    215     }
    216 
    217     /**
    218      * java.io.PrintStream#flush()
    219      */
    220     public void test_flush() throws Exception {
    221         // Test for method void java.io.PrintStream.flush()
    222         PrintStream os = new PrintStream(bos);
    223         os.print(fileString.substring(0, 501));
    224         os.flush();
    225         assertEquals("Bytes not written after flush", 501, bos.size());
    226         bos.close();
    227         os.close();
    228     }
    229 
    230     /**
    231      * java.io.PrintStream#print(char[])
    232      */
    233     public void test_print$C() {
    234         // Test for method void java.io.PrintStream.print(char [])
    235         PrintStream os = new PrintStream(bos, true);
    236         try {
    237             os.print((char[]) null);
    238             fail("NPE expected");
    239         } catch (NullPointerException ok) {
    240         }
    241 
    242         os = new PrintStream(bos, true);
    243         char[] sc = new char[4000];
    244         fileString.getChars(0, fileString.length(), sc, 0);
    245         os.print(sc);
    246         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    247         os.close();
    248 
    249         byte[] rbytes = new byte[4000];
    250         bis.read(rbytes, 0, fileString.length());
    251         assertEquals("Incorrect char[] written", fileString, new String(rbytes,
    252                 0, fileString.length()));
    253     }
    254 
    255     /**
    256      * java.io.PrintStream#print(char)
    257      */
    258     public void test_printC() throws Exception {
    259         // Test for method void java.io.PrintStream.print(char)
    260         PrintStream os = new PrintStream(bos, true);
    261         os.print('t');
    262         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    263         InputStreamReader isr = new InputStreamReader(bis);
    264         assertEquals("Incorrect char written", 't', isr.read());
    265     }
    266 
    267     /**
    268      * java.io.PrintStream#print(double)
    269      */
    270     public void test_printD() {
    271         // Test for method void java.io.PrintStream.print(double)
    272         byte[] rbuf = new byte[100];
    273         PrintStream os = new PrintStream(bos, true);
    274         os.print(2345.76834720202);
    275         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    276         bis.read(rbuf, 0, 16);
    277         assertEquals("Incorrect double written", "2345.76834720202",
    278                 new String(rbuf, 0, 16));
    279     }
    280 
    281     /**
    282      * java.io.PrintStream#print(float)
    283      */
    284     public void test_printF() {
    285         // Test for method void java.io.PrintStream.print(float)
    286         PrintStream os = new PrintStream(bos, true);
    287         byte rbuf[] = new byte[10];
    288         os.print(29.08764f);
    289         os.flush();
    290         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    291         bis.read(rbuf, 0, 8);
    292         assertEquals("Incorrect float written", "29.08764", new String(rbuf, 0,
    293                 8));
    294 
    295     }
    296 
    297     /**
    298      * java.io.PrintStream#print(int)
    299      */
    300     public void test_printI() {
    301         // Test for method void java.io.PrintStream.print(int)
    302         PrintStream os = new PrintStream(bos, true);
    303         os.print(768347202);
    304         byte[] rbuf = new byte[18];
    305         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    306         bis.read(rbuf, 0, 9);
    307         assertEquals("Incorrect int written", "768347202", new String(rbuf, 0,
    308                 9));
    309     }
    310 
    311     /**
    312      * java.io.PrintStream#print(long)
    313      */
    314     public void test_printJ() {
    315         // Test for method void java.io.PrintStream.print(long)
    316         byte[] rbuf = new byte[100];
    317         PrintStream os = new PrintStream(bos, true);
    318         os.print(9875645283333L);
    319         os.close();
    320         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    321         bis.read(rbuf, 0, 13);
    322         assertEquals("Incorrect long written", "9875645283333", new String(
    323                 rbuf, 0, 13));
    324     }
    325 
    326     /**
    327      * java.io.PrintStream#print(java.lang.Object)
    328      */
    329     public void test_printLjava_lang_Object() throws Exception {
    330         // Test for method void java.io.PrintStream.print(java.lang.Object)
    331         PrintStream os = new PrintStream(bos, true);
    332         os.print((Object) null);
    333         os.flush();
    334         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    335         byte[] nullbytes = new byte[4];
    336         bis.read(nullbytes, 0, 4);
    337         assertEquals("null should be written", "null", new String(nullbytes, 0,
    338                 4));
    339 
    340         bis.close();
    341         bos.close();
    342         os.close();
    343 
    344         ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
    345         os = new PrintStream(bos1, true);
    346         os.print(new java.util.Vector());
    347         bis = new ByteArrayInputStream(bos1.toByteArray());
    348         byte[] rbytes = new byte[2];
    349         bis.read(rbytes, 0, 2);
    350         assertEquals("Incorrect Object written", "[]", new String(rbytes, 0, 2));
    351     }
    352 
    353     /**
    354      * java.io.PrintStream#print(java.lang.String)
    355      */
    356     public void test_printLjava_lang_String() throws Exception {
    357         // Test for method void java.io.PrintStream.print(java.lang.String)
    358         PrintStream os = new PrintStream(bos, true);
    359         os.print((String) null);
    360         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    361         byte[] nullbytes = new byte[4];
    362         bis.read(nullbytes, 0, 4);
    363         assertEquals("null should be written", "null", new String(nullbytes, 0,
    364                 4));
    365 
    366         bis.close();
    367         bos.close();
    368         os.close();
    369 
    370         ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
    371         os = new PrintStream(bos1, true);
    372         os.print("Hello World");
    373         bis = new ByteArrayInputStream(bos1.toByteArray());
    374         byte rbytes[] = new byte[100];
    375         bis.read(rbytes, 0, 11);
    376         assertEquals("Incorrect string written", "Hello World", new String(
    377                 rbytes, 0, 11));
    378     }
    379 
    380     /**
    381      * java.io.PrintStream#print(boolean)
    382      */
    383     public void test_printZ() throws Exception {
    384         // Test for method void java.io.PrintStream.print(boolean)
    385         PrintStream os = new PrintStream(bos, true);
    386         os.print(true);
    387         DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bos
    388                 .toByteArray()));
    389 
    390         assertTrue("Incorrect boolean written", dis.readBoolean());
    391     }
    392 
    393     /**
    394      * java.io.PrintStream#println()
    395      */
    396     public void test_println() throws Exception {
    397         // Test for method void java.io.PrintStream.println()
    398         char c;
    399         PrintStream os = new PrintStream(bos, true);
    400         os.println("");
    401         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    402         InputStreamReader isr = new InputStreamReader(bis);
    403         assertTrue("Newline not written", (c = (char) isr.read()) == '\r'
    404                 || c == '\n');
    405     }
    406 
    407     /**
    408      * java.io.PrintStream#println(char[])
    409      */
    410     public void test_println$C() throws Exception {
    411         // Test for method void java.io.PrintStream.println(char [])
    412         PrintStream os = new PrintStream(bos, true);
    413         char[] sc = new char[4000];
    414         fileString.getChars(0, fileString.length(), sc, 0);
    415         os.println(sc);
    416         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    417         InputStreamReader isr = new InputStreamReader(bis);
    418         byte[] rbytes = new byte[4000];
    419         bis.read(rbytes, 0, fileString.length());
    420         assertEquals("Incorrect char[] written", fileString, new String(rbytes,
    421                 0, fileString.length()));
    422 
    423         // In this particular test method, the end of data is not immediately
    424         // followed by newLine separator in the reading buffer, instead its
    425         // followed by zeros. The newline is written as the last entry
    426         // in the inputStream buffer. Therefore, we must keep reading until we
    427         // hit a new line.
    428         int r;
    429         boolean newline = false;
    430         while ((r = isr.read()) != -1) {
    431             if (r == '\r' || r == '\n')
    432                 newline = true;
    433         }
    434         assertTrue("Newline not written", newline);
    435     }
    436 
    437     /**
    438      * java.io.PrintStream#println(char)
    439      */
    440     public void test_printlnC() throws Exception {
    441         // Test for method void java.io.PrintStream.println(char)
    442         int c;
    443         PrintStream os = new PrintStream(bos, true);
    444         os.println('t');
    445         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    446         InputStreamReader isr = new InputStreamReader(bis);
    447         assertEquals("Incorrect char written", 't', isr.read());
    448         assertTrue("Newline not written", (c = isr.read()) == '\r' || c == '\n');
    449     }
    450 
    451     /**
    452      * java.io.PrintStream#println(double)
    453      */
    454     public void test_printlnD() throws Exception {
    455         // Test for method void java.io.PrintStream.println(double)
    456         int c;
    457         PrintStream os = new PrintStream(bos, true);
    458         os.println(2345.76834720202);
    459         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    460         InputStreamReader isr = new InputStreamReader(bis);
    461         byte[] rbuf = new byte[100];
    462         bis.read(rbuf, 0, 16);
    463         assertEquals("Incorrect double written", "2345.76834720202",
    464                 new String(rbuf, 0, 16));
    465         assertTrue("Newline not written", (c = isr.read()) == '\r' || c == '\n');
    466     }
    467 
    468     /**
    469      * java.io.PrintStream#println(float)
    470      */
    471     public void test_printlnF() throws Exception {
    472         // Test for method void java.io.PrintStream.println(float)
    473         int c;
    474         byte[] rbuf = new byte[100];
    475         PrintStream os = new PrintStream(bos, true);
    476         os.println(29.08764f);
    477         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    478         InputStreamReader isr = new InputStreamReader(bis);
    479         bis.read(rbuf, 0, 8);
    480         assertEquals("Incorrect float written", "29.08764", new String(rbuf, 0,
    481                 8));
    482         assertTrue("Newline not written", (c = isr.read()) == '\r' || c == '\n');
    483     }
    484 
    485     /**
    486      * java.io.PrintStream#println(int)
    487      */
    488     public void test_printlnI() throws Exception {
    489         // Test for method void java.io.PrintStream.println(int)
    490         int c;
    491         PrintStream os = new PrintStream(bos, true);
    492         os.println(768347202);
    493         byte[] rbuf = new byte[100];
    494         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    495         InputStreamReader isr = new InputStreamReader(bis);
    496         bis.read(rbuf, 0, 9);
    497         assertEquals("Incorrect int written", "768347202", new String(rbuf, 0,
    498                 9));
    499         assertTrue("Newline not written", (c = isr.read()) == '\r' || c == '\n');
    500     }
    501 
    502     /**
    503      * java.io.PrintStream#println(long)
    504      */
    505     public void test_printlnJ() throws Exception {
    506         // Test for method void java.io.PrintStream.println(long)
    507         int c;
    508         PrintStream os = new PrintStream(bos, true);
    509         os.println(9875645283333L);
    510         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    511         InputStreamReader isr = new InputStreamReader(bis);
    512         byte[] rbuf = new byte[100];
    513         bis.read(rbuf, 0, 13);
    514         assertEquals("Incorrect long written", "9875645283333", new String(
    515                 rbuf, 0, 13));
    516         assertTrue("Newline not written", (c = isr.read()) == '\r' || c == '\n');
    517     }
    518 
    519     /**
    520      * java.io.PrintStream#println(java.lang.Object)
    521      */
    522     public void test_printlnLjava_lang_Object() throws Exception {
    523         // Test for method void java.io.PrintStream.println(java.lang.Object)
    524         char c;
    525         PrintStream os = new PrintStream(bos, true);
    526         os.println(new java.util.Vector());
    527         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    528         InputStreamReader isr = new InputStreamReader(bis);
    529         byte[] rbytes = new byte[2];
    530         bis.read(rbytes, 0, 2);
    531         assertEquals("Incorrect Vector written", "[]", new String(rbytes, 0, 2));
    532         assertTrue("Newline not written", (c = (char) isr.read()) == '\r'
    533                 || c == '\n');
    534     }
    535 
    536     /**
    537      * java.io.PrintStream#println(java.lang.String)
    538      */
    539     public void test_printlnLjava_lang_String() throws Exception {
    540         // Test for method void java.io.PrintStream.println(java.lang.String)
    541         char c;
    542         PrintStream os = new PrintStream(bos, true);
    543         os.println("Hello World");
    544         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    545         InputStreamReader isr = new InputStreamReader(bis);
    546         byte rbytes[] = new byte[100];
    547         bis.read(rbytes, 0, 11);
    548         assertEquals("Incorrect string written", "Hello World", new String(
    549                 rbytes, 0, 11));
    550         assertTrue("Newline not written", (c = (char) isr.read()) == '\r'
    551                 || c == '\n');
    552     }
    553 
    554     /**
    555      * java.io.PrintStream#println(boolean)
    556      */
    557     public void test_printlnZ() throws Exception {
    558         // Test for method void java.io.PrintStream.println(boolean)
    559         int c;
    560         PrintStream os = new PrintStream(bos, true);
    561         os.println(true);
    562         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    563         InputStreamReader isr = new InputStreamReader(bis);
    564         byte[] rbuf = new byte[100];
    565         bis.read(rbuf, 0, 4);
    566         assertEquals("Incorrect boolean written", "true",
    567                 new String(rbuf, 0, 4));
    568         assertTrue("Newline not written", (c = isr.read()) == '\r' || c == '\n');
    569     }
    570 
    571     /**
    572      * java.io.PrintStream#write(byte[], int, int)
    573      */
    574     public void test_write$BII() {
    575         // Test for method void java.io.PrintStream.write(byte [], int, int)
    576         PrintStream os = new PrintStream(bos, true);
    577         os.write(fileString.getBytes(), 0, fileString.length());
    578         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    579         byte rbytes[] = new byte[4000];
    580         bis.read(rbytes, 0, fileString.length());
    581         assertTrue("Incorrect bytes written", new String(rbytes, 0, fileString
    582                 .length()).equals(fileString));
    583     }
    584 
    585     /**
    586      * java.io.PrintStream#write(int)
    587      */
    588     public void test_writeI() {
    589         // Test for method void java.io.PrintStream.write(int)
    590         PrintStream os = new PrintStream(bos, true);
    591         os.write('t');
    592         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    593         assertEquals("Incorrect char written", 't', bis.read());
    594     }
    595 
    596     /**
    597      * java.io.PrintStream#append(char)
    598      */
    599     public void test_appendChar() throws IOException {
    600         char testChar = ' ';
    601         ByteArrayOutputStream out = new ByteArrayOutputStream();
    602         PrintStream printStream = new PrintStream(out);
    603         printStream.append(testChar);
    604         printStream.flush();
    605         assertEquals(String.valueOf(testChar), out.toString());
    606         printStream.close();
    607     }
    608 
    609     /**
    610      * java.io.PrintStream#append(CharSequence)
    611      */
    612     public void test_appendCharSequence() {
    613         String testString = "My Test String";
    614         ByteArrayOutputStream out = new ByteArrayOutputStream();
    615         PrintStream printStream = new PrintStream(out);
    616         printStream.append(testString);
    617         printStream.flush();
    618         assertEquals(testString, out.toString());
    619         printStream.close();
    620     }
    621 
    622     /**
    623      * java.io.PrintStream#append(CharSequence, int, int)
    624      */
    625     public void test_appendCharSequenceIntInt() {
    626         String testString = "My Test String";
    627         ByteArrayOutputStream out = new ByteArrayOutputStream();
    628         PrintStream printStream = new PrintStream(out);
    629         printStream.append(testString, 1, 3);
    630         printStream.flush();
    631         assertEquals(testString.substring(1, 3), out.toString());
    632         printStream.close();
    633     }
    634 
    635     /**
    636      * java.io.PrintStream#format(java.lang.String, java.lang.Object...)
    637      */
    638     public void test_formatLjava_lang_String$Ljava_lang_Object() {
    639         PrintStream os = new PrintStream(bos, false);
    640         os.format("%s %s", "Hello", "World");
    641         os.flush();
    642         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    643         byte[] rbytes = new byte[11];
    644         bis.read(rbytes, 0, rbytes.length);
    645         assertEquals("Wrote incorrect string", "Hello World",
    646                 new String(rbytes));
    647 
    648     }
    649 
    650     /**
    651      * java.io.PrintStream#format(java.util.Locale, java.lang.String,
    652      *java.lang.Object...)
    653      */
    654     public void test_formatLjava_util_Locale_Ljava_lang_String_$Ljava_lang_Object() {
    655         PrintStream os = new PrintStream(bos, false);
    656         os.format(Locale.US, "%s %s", "Hello", "World");
    657         os.flush();
    658         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    659         byte[] rbytes = new byte[11];
    660         bis.read(rbytes, 0, rbytes.length);
    661         assertEquals("Wrote incorrect string", "Hello World",
    662                 new String(rbytes));
    663     }
    664 
    665     /**
    666      * Tests that a PrintStream with {@code autoFlush == true} will call
    667      * {@link OutputStream#flush()} at least once, after the last byte
    668      * was written.
    669      */
    670     public void test_autoFlush_flushesEverything() {
    671         CountFlushOutputStream counter = new CountFlushOutputStream(new ByteArrayOutputStream());
    672         PrintStream printStream = new PrintStream(counter, true /* autoFlush */);
    673         printStream.print("Hello, world!");
    674         assertTrue(counter.hasBeenFlushedSinceLastWrite());
    675         printStream.print(Math.PI);
    676         assertTrue(counter.hasBeenFlushedSinceLastWrite());
    677         printStream.print("\n");
    678         assertTrue(counter.hasBeenFlushedSinceLastWrite());
    679         printStream.println();
    680         assertTrue(counter.hasBeenFlushedSinceLastWrite());
    681         printStream.println("Lots\nof\nnewlines\n");
    682         assertTrue(counter.hasBeenFlushedSinceLastWrite());
    683         printStream.print("Line 1\nLine 2\n".toCharArray());
    684         assertTrue(counter.hasBeenFlushedSinceLastWrite());
    685 
    686         byte[] bytes = "Line without a newline".getBytes(StandardCharsets.UTF_8);
    687         printStream.write(bytes, 0, bytes.length);
    688         assertTrue(counter.hasBeenFlushedSinceLastWrite());
    689     }
    690 
    691     /**
    692      * Tests that a PrintStream with {@code autoFlush == false} will not
    693      * call {@link OutputStream#flush()} in regular (non-error) operation.
    694      */
    695     public void test_noAutoFlush() {
    696         CountFlushOutputStream counter = new CountFlushOutputStream(new ByteArrayOutputStream());
    697         PrintStream printStream = new PrintStream(counter, false /* autoFlush */);
    698         printStream.print("Hello, world!");
    699         printStream.print(Math.PI);
    700         printStream.print("\n");
    701         printStream.println();
    702         printStream.println("Lots\nof\nnewlines\n");
    703         printStream.print("Line 1\nLine 2\n".toCharArray());
    704         byte[] bytes = "Line without a newline".getBytes(StandardCharsets.UTF_8);
    705         printStream.write(bytes, 0, bytes.length);
    706         assertFalse(counter.hasEverBeenFlushed());
    707         assertFalse(counter.hasBeenFlushedSinceLastWrite());
    708 
    709         // checkError() still causes the PrintStream to flush(), even when autoFlush == false.
    710         printStream.checkError();
    711         assertTrue(counter.hasEverBeenFlushed());
    712         assertTrue(counter.hasBeenFlushedSinceLastWrite());
    713         printStream.print("This data\nwill not be flushed.");
    714         assertTrue(counter.hasEverBeenFlushed());
    715         assertFalse(counter.hasBeenFlushedSinceLastWrite());
    716     }
    717 
    718     /**
    719      * java.io.PrintStream#printf(java.lang.String, java.lang.Object...)
    720      */
    721     public void test_printfLjava_lang_String$Ljava_lang_Object() {
    722         PrintStream os = new PrintStream(bos, false);
    723         os.printf("%s %s", "Hello", "World");
    724         os.flush();
    725         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    726         byte[] rbytes = new byte[11];
    727         bis.read(rbytes, 0, rbytes.length);
    728         assertEquals("Wrote incorrect string", "Hello World",
    729                 new String(rbytes));
    730     }
    731 
    732     /**
    733      * java.io.PrintStream#printf(java.util.Locale, java.lang.String,
    734      *java.lang.Object...)
    735      */
    736     public void test_printfLjava_util_Locale_Ljava_lang_String_$Ljava_lang_Object() {
    737         PrintStream os = new PrintStream(bos, false);
    738         os.printf(Locale.US, "%s %s", "Hello", "World");
    739         os.flush();
    740         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    741         byte[] rbytes = new byte[11];
    742         bis.read(rbytes, 0, rbytes.length);
    743         assertEquals("Wrote incorrect string", "Hello World",
    744                 new String(rbytes));
    745     }
    746 
    747     @Override
    748     protected void setUp() throws Exception {
    749         super.setUp();
    750         testFile = File.createTempFile("test", null);
    751         testFilePath = testFile.getAbsolutePath();
    752     }
    753 
    754     @Override
    755     protected void tearDown() throws Exception {
    756         testFile.delete();
    757         testFile = null;
    758         testFilePath = null;
    759         super.tearDown();
    760     }
    761 
    762     private static void assertByteArraysEqual(byte[] expected, byte[] actual) {
    763         String message = "Expected " + Base64.getEncoder().encodeToString(expected) + ", got: "
    764                 + Base64.getEncoder().encodeToString(actual);
    765         assertTrue(message, Arrays.equals(actual, expected));
    766     }
    767 
    768     private static void assertFileContents(byte[] expected, File file) throws IOException {
    769         byte[] actual = IoUtils.readFileAsByteArray(file.getAbsolutePath());
    770         assertByteArraysEqual(expected, actual);
    771     }
    772 
    773     static class CountFlushOutputStream extends FilterOutputStream {
    774         private boolean hasBeenFlushedSinceLastWrite = false;
    775         private boolean hasEverBeenFlushed = false;
    776 
    777         public CountFlushOutputStream(OutputStream delegate) {
    778             super(delegate);
    779         }
    780 
    781         @Override
    782         public void write(int b) throws IOException {
    783             super.write(b);
    784             hasBeenFlushedSinceLastWrite = false;
    785         }
    786 
    787         @Override
    788         public void flush() throws IOException {
    789             super.flush();
    790             hasBeenFlushedSinceLastWrite = true;
    791             hasEverBeenFlushed = true;
    792         }
    793 
    794         /** Whether {@link #flush()} has been called since the last write. */
    795         public boolean hasBeenFlushedSinceLastWrite() {
    796             return hasBeenFlushedSinceLastWrite;
    797         }
    798 
    799         /** Whether {@link #flush()} has ever been called after this stream was constructed. */
    800         public boolean hasEverBeenFlushed() {
    801             return hasEverBeenFlushed;
    802         }
    803     }
    804 
    805 }
    806