OSDN Git Service

original
[gb-231r1-is01/Gingerbread_2.3.3_r1_IS01.git] / libcore / luni / src / test / java / org / apache / harmony / luni / tests / java / io / OutputStreamWriterTest.java
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.luni.tests.java.io;
19
20 import java.io.ByteArrayInputStream;
21 import java.io.ByteArrayOutputStream;
22 import java.io.File;
23 import java.io.FileInputStream;
24 import java.io.FileReader;
25 import java.io.FileWriter;
26 import java.io.IOException;
27 import java.io.InputStreamReader;
28 import java.io.OutputStreamWriter;
29 import java.io.UnsupportedEncodingException;
30 import java.nio.charset.Charset;
31 import java.nio.charset.CharsetEncoder;
32
33 import junit.framework.TestCase;
34
35 public class OutputStreamWriterTest extends TestCase {
36
37     private static final int UPPER = 0xd800;
38
39     private static final int BUFFER_SIZE = 10000;
40
41     private ByteArrayOutputStream out;
42
43     private OutputStreamWriter writer;
44
45     static private final String source = "This is a test message with Unicode character. \u4e2d\u56fd is China's name in Chinese";
46
47     static private final String[] MINIMAL_CHARSETS = new String[] { "US-ASCII",
48             "ISO-8859-1", "UTF-16BE", "UTF-16LE", "UTF-16", "UTF-8" };
49
50     OutputStreamWriter osw;
51
52     InputStreamReader isr;
53
54     private ByteArrayOutputStream fos;
55
56     String testString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\n";
57
58     /*
59      * @see TestCase#setUp()
60      */
61     @Override
62     protected void setUp() throws Exception {
63         super.setUp();
64         out = new ByteArrayOutputStream();
65         writer = new OutputStreamWriter(out, "utf-8");
66
67         fos = new ByteArrayOutputStream();
68         osw = new OutputStreamWriter(fos);
69     }
70
71     /*
72      * @see TestCase#tearDown()
73      */
74     @Override
75     protected void tearDown() throws Exception {
76         try {
77             writer.close();
78
79             if (isr != null) {
80                 isr.close();
81             }
82             osw.close();
83         } catch (Exception e) {
84             // Ignored
85         }
86
87         super.tearDown();
88     }
89
90     public void testClose() throws Exception {
91         writer.flush();
92         writer.close();
93         try {
94             writer.flush();
95             fail();
96         } catch (IOException e) {
97             // Expected
98         }
99     }
100
101     public void testFlush() throws Exception {
102         writer.write(source);
103         writer.flush();
104         String result = out.toString("utf-8");
105         assertEquals(source, result);
106     }
107
108     /*
109      * Class under test for void write(char[], int, int)
110      */
111     public void testWritecharArrayintint() throws IOException {
112         char[] chars = source.toCharArray();
113
114         // Throws IndexOutOfBoundsException if offset is negative
115         try {
116             writer.write((char[]) null, -1, -1);
117             fail("should throw IndexOutOfBoundsException");
118         } catch (IndexOutOfBoundsException e) {
119             // Expected
120         }
121
122         // throws NullPointerException though count is negative
123         try {
124             writer.write((char[]) null, 1, -1);
125             fail("should throw NullPointerException");
126         } catch (NullPointerException e) {
127             // Expected
128         }
129
130         try {
131             writer.write((char[]) null, 1, 1);
132             fail();
133         } catch (NullPointerException e) {
134             // Expected
135         }
136         try {
137             writer.write(new char[0], 0, 1);
138             fail();
139         } catch (IndexOutOfBoundsException e) {
140             // Expected
141         }
142         try {
143             writer.write(chars, -1, 1);
144             fail();
145         } catch (IndexOutOfBoundsException e) {
146             // Expected
147         }
148         try {
149             writer.write(chars, 0, -1);
150             fail();
151         } catch (IndexOutOfBoundsException e) {
152             // Expected
153         }
154         try {
155             writer.write(chars, 1, chars.length);
156             fail();
157         } catch (IndexOutOfBoundsException e) {
158             // Expected
159         }
160         writer.write(chars, 1, 2);
161         writer.flush();
162         assertEquals("hi", out.toString("utf-8"));
163         writer.write(chars, 0, chars.length);
164         writer.flush();
165         assertEquals("hi" + source, out.toString("utf-8"));
166
167         writer.close();
168         // After the stream is closed, should throw IOException first
169         try {
170             writer.write((char[]) null, -1, -1);
171             fail("should throw IOException");
172         } catch (IOException e) {
173             // Expected
174         }
175     }
176
177     /*
178      * Class under test for void write(int)
179      */
180     public void testWriteint() throws IOException {
181         writer.write(1);
182         writer.flush();
183         String str = new String(out.toByteArray(), "utf-8");
184         assertEquals("\u0001", str);
185
186         writer.write(2);
187         writer.flush();
188         str = new String(out.toByteArray(), "utf-8");
189         assertEquals("\u0001\u0002", str);
190
191         writer.write(-1);
192         writer.flush();
193         str = new String(out.toByteArray(), "utf-8");
194         assertEquals("\u0001\u0002\uffff", str);
195
196         writer.write(0xfedcb);
197         writer.flush();
198         str = new String(out.toByteArray(), "utf-8");
199         assertEquals("\u0001\u0002\uffff\uedcb", str);
200
201         writer.close();
202         // After the stream is closed, should throw IOException
203         try {
204             writer.write(1);
205             fail("should throw IOException");
206         } catch (IOException e) {
207             // expected
208         }
209     }
210
211     /*
212      * Class under test for void write(String, int, int)
213      */
214     public void testWriteStringintint() throws IOException {
215         try {
216             writer.write((String) null, 1, 1);
217             fail();
218         } catch (NullPointerException e) {
219             // Expected
220         }
221         try {
222             writer.write("", 0, 1);
223             fail();
224         } catch (StringIndexOutOfBoundsException e) {
225             // Expected
226         }
227         try {
228             writer.write("abc", -1, 1);
229             fail();
230         } catch (StringIndexOutOfBoundsException e) {
231             // Expected
232         }
233         try {
234             writer.write("abc", 0, -1);
235             fail();
236         } catch (IndexOutOfBoundsException e) {
237             // Expected
238         }
239         try {
240             writer.write("abc", 1, 3);
241             fail();
242         } catch (StringIndexOutOfBoundsException e) {
243             // Expected
244         }
245
246         // Throws IndexOutOfBoundsException before NullPointerException if count
247         // is negative
248         try {
249             writer.write((String) null, -1, -1);
250             fail("should throw IndexOutOfBoundsException");
251         } catch (IndexOutOfBoundsException e) {
252             // Expected
253         }
254
255         // Throws NullPointerException before StringIndexOutOfBoundsException
256         try {
257             writer.write((String) null, -1, 0);
258             fail("should throw NullPointerException");
259         } catch (NullPointerException e) {
260             // expected
261         }
262
263         writer.write("abc", 1, 2);
264         writer.flush();
265         assertEquals("bc", out.toString("utf-8"));
266         writer.write(source, 0, source.length());
267         writer.flush();
268         assertEquals("bc" + source, out.toString("utf-8"));
269
270         writer.close();
271         // Throws IndexOutOfBoundsException first if count is negative
272         try {
273             writer.write((String) null, 0, -1);
274             fail("should throw IndexOutOfBoundsException");
275         } catch (IndexOutOfBoundsException e) {
276             // Expected
277         }
278
279         try {
280             writer.write((String) null, -1, 0);
281             fail("should throw NullPointerException");
282         } catch (NullPointerException e) {
283             // Expected
284         }
285
286         try {
287             writer.write("abc", -1, 0);
288             fail("should throw StringIndexOutOfBoundsException");
289         } catch (StringIndexOutOfBoundsException e) {
290             // Expected
291         }
292
293         // Throws IOException
294         try {
295             writer.write("abc", 0, 1);
296             fail("should throw IOException");
297         } catch (IOException e) {
298             // expected
299         }
300     }
301
302     /*
303      * Class under test for void OutputStreamWriter(OutputStream)
304      */
305     public void testOutputStreamWriterOutputStream() throws IOException {
306         try {
307             writer = new OutputStreamWriter(null);
308             fail();
309         } catch (NullPointerException e) {
310             // Expected
311         }
312         OutputStreamWriter writer2 = new OutputStreamWriter(out);
313         writer2.close();
314     }
315
316     /*
317      * Class under test for void OutputStreamWriter(OutputStream, String)
318      */
319     public void testOutputStreamWriterOutputStreamString() throws IOException {
320         try {
321             writer = new OutputStreamWriter(null, "utf-8");
322             fail();
323         } catch (NullPointerException e) {
324             // Expected
325         }
326         try {
327             writer = new OutputStreamWriter(out, "");
328             fail();
329         } catch (UnsupportedEncodingException e) {
330             // Expected
331         }
332         try {
333             writer = new OutputStreamWriter(out, "badname");
334             fail();
335         } catch (UnsupportedEncodingException e) {
336             // Expected
337         }
338         try {
339             writer = new OutputStreamWriter(out, (String) null);
340             fail();
341         } catch (NullPointerException e) {
342             // Expected
343         }
344         OutputStreamWriter writer2 = new OutputStreamWriter(out, "ascii");
345         assertEquals(Charset.forName("ascii"), Charset.forName(writer2
346                 .getEncoding()));
347         writer2.close();
348     }
349
350     /*
351      * Class under test for void OutputStreamWriter(OutputStream)
352      */
353     public void testOutputStreamWriterOutputStreamCharset() throws IOException {
354         Charset cs = Charset.forName("ascii");
355         try {
356             writer = new OutputStreamWriter(null, cs);
357             fail();
358         } catch (NullPointerException e) {
359             // Expected
360         }
361         try {
362             writer = new OutputStreamWriter(out, (Charset) null);
363             fail();
364         } catch (NullPointerException e) {
365             // Expected
366         }
367         OutputStreamWriter writer2 = new OutputStreamWriter(out, cs);
368         assertEquals(cs, Charset.forName(writer2.getEncoding()));
369         writer2.close();
370     }
371
372     /*
373      * Class under test for void OutputStreamWriter(OutputStream, String)
374      */
375     public void testOutputStreamWriterOutputStreamCharsetEncoder()
376             throws IOException {
377         Charset cs = Charset.forName("ascii");
378         CharsetEncoder enc = cs.newEncoder();
379         try {
380             writer = new OutputStreamWriter(null, enc);
381             fail();
382         } catch (NullPointerException e) {
383             // Expected
384         }
385         try {
386             writer = new OutputStreamWriter(out, (CharsetEncoder) null);
387             fail();
388         } catch (NullPointerException e) {
389             // Expected
390         }
391         OutputStreamWriter writer2 = new OutputStreamWriter(out, enc);
392         assertEquals(cs, Charset.forName(writer2.getEncoding()));
393         writer2.close();
394     }
395
396     public void testGetEncoding() {
397         Charset cs = Charset.forName("utf-8");
398         assertEquals(cs, Charset.forName(writer.getEncoding()));
399     }
400
401     public void testHandleEarlyEOFChar_1() throws IOException {
402         String str = "All work and no play makes Jack a dull boy\n";
403         int NUMBER = 2048;
404         int j = 0;
405         int len = str.length() * NUMBER;
406         char[] strChars = new char[len];
407         for (int i = 0; i < NUMBER; ++i) {
408             for (int k = 0; k < str.length(); ++k) {
409                 strChars[j++] = str.charAt(k);
410             }
411         }
412
413         File f = File.createTempFile("one", "by_one");
414         f.deleteOnExit();
415         FileWriter fw = new FileWriter(f);
416         fw.write(strChars);
417         fw.close();
418         FileInputStream fis = new FileInputStream(f);
419         InputStreamReader in = new InputStreamReader(fis);
420         for (int offset = 0; offset < strChars.length; ++offset) {
421             int b = in.read();
422             assertFalse("Early EOF at offset", -1 == b);
423         }
424     }
425
426     public void testHandleEarlyEOFChar_2() throws IOException {
427         int capacity = 65536;
428         byte[] bytes = new byte[capacity];
429         byte[] bs = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H' };
430         for (int i = 0; i < bytes.length; i++) {
431             bytes[i] = bs[i / 8192];
432         }
433         String inputStr = new String(bytes);
434         int len = inputStr.length();
435         File f = File.createTempFile("FileWriterBugTest ", null);
436         f.deleteOnExit();
437         FileWriter writer = new FileWriter(f);
438         writer.write(inputStr);
439         writer.close();
440         long flen = f.length();
441
442         FileReader reader = new FileReader(f);
443         char[] outChars = new char[capacity];
444         int outCount = reader.read(outChars);
445         String outStr = new String(outChars, 0, outCount);
446
447         assertEquals(len, flen);
448         assertEquals(inputStr, outStr);
449     }
450
451     public void testSingleCharIO() throws Exception {
452         InputStreamReader isr = null;
453         for (int i = 0; i < MINIMAL_CHARSETS.length; ++i) {
454             try {
455                 out = new ByteArrayOutputStream();
456                 writer = new OutputStreamWriter(out, MINIMAL_CHARSETS[i]);
457
458                 int upper = UPPER;
459                 switch (i) {
460                 case 0:
461                     upper = 128;
462                     break;
463                 case 1:
464                     upper = 256;
465                     break;
466                 }
467
468                 for (int c = 0; c < upper; ++c) {
469                     writer.write(c);
470                 }
471                 writer.flush();
472                 byte[] result = out.toByteArray();
473
474                 isr = new InputStreamReader(new ByteArrayInputStream(result),
475                         MINIMAL_CHARSETS[i]);
476                 for (int expected = 0; expected < upper; ++expected) {
477                     assertEquals("Error when reading bytes in "
478                             + MINIMAL_CHARSETS[i], expected, isr.read());
479                 }
480             } finally {
481                 try {
482                     isr.close();
483                 } catch (Exception e) {
484                 }
485                 try {
486                     writer.close();
487                 } catch (Exception e) {
488                 }
489             }
490         }
491     }
492
493     public void testBlockIO() throws Exception {
494         InputStreamReader isr = null;
495         char[] largeBuffer = new char[BUFFER_SIZE];
496         for (int i = 0; i < MINIMAL_CHARSETS.length; ++i) {
497             try {
498                 out = new ByteArrayOutputStream();
499                 writer = new OutputStreamWriter(out, MINIMAL_CHARSETS[i]);
500
501                 int upper = UPPER;
502                 switch (i) {
503                 case 0:
504                     upper = 128;
505                     break;
506                 case 1:
507                     upper = 256;
508                     break;
509                 }
510
511                 int m = 0;
512                 for (int c = 0; c < upper; ++c) {
513                     largeBuffer[m++] = (char) c;
514                     if (m == BUFFER_SIZE) {
515                         writer.write(largeBuffer);
516                         m = 0;
517                     }
518                 }
519                 writer.write(largeBuffer, 0, m);
520                 writer.flush();
521                 byte[] result = out.toByteArray();
522
523                 isr = new InputStreamReader(new ByteArrayInputStream(result),
524                         MINIMAL_CHARSETS[i]);
525                 int expected = 0, read = 0, j = 0;
526                 while (expected < upper) {
527                     if (j == read) {
528                         read = isr.read(largeBuffer);
529                         j = 0;
530                     }
531                     assertEquals("Error when reading bytes in "
532                             + MINIMAL_CHARSETS[i], expected++, largeBuffer[j++]);
533                 }
534             } finally {
535                 try {
536                     isr.close();
537                 } catch (Exception e) {
538                 }
539                 try {
540                     writer.close();
541                 } catch (Exception e) {
542                 }
543             }
544         }
545     }
546
547     /**
548      * @tests java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream)
549      */
550     public void test_ConstructorLjava_io_OutputStream() {
551         assertTrue("Used in tests", true);
552     }
553
554     /**
555      * @tests java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream,
556      *        java.lang.String)
557      */
558     public void test_ConstructorLjava_io_OutputStreamLjava_lang_String()
559             throws UnsupportedEncodingException {
560         osw = new OutputStreamWriter(fos, "8859_1");
561         try {
562             osw = new OutputStreamWriter(fos, "Bogus");
563             fail("Failed to throw Unsupported Encoding exception");
564         } catch (UnsupportedEncodingException e) {
565             // Expected
566         }
567     }
568
569     /**
570      * @tests java.io.OutputStreamWriter#close()
571      */
572     public void test_close() throws IOException {
573         osw.close();
574
575         try {
576             osw.write(testString, 0, testString.length());
577             fail("Chars written after close");
578         } catch (IOException e) {
579             // Expected
580         }
581
582         ByteArrayOutputStream bout = new ByteArrayOutputStream();
583         try {
584             OutputStreamWriter writer = new OutputStreamWriter(bout,
585                     "ISO2022JP");
586             writer.write(new char[] { 'a' });
587             writer.close();
588             // the default is ASCII, there should not be any mode changes
589             String converted = new String(bout.toByteArray(), "ISO8859_1");
590             assertTrue("invalid conversion 1: " + converted, converted
591                     .equals("a"));
592
593             bout.reset();
594             writer = new OutputStreamWriter(bout, "ISO2022JP");
595             writer.write(new char[] { '\u3048' });
596             writer.flush();
597             // the byte sequence should not switch to ASCII mode until the
598             // stream is closed
599             converted = new String(bout.toByteArray(), "ISO8859_1");
600             assertTrue("invalid conversion 2: " + converted, converted
601                     .equals("\u001b$B$("));
602             writer.close();
603             converted = new String(bout.toByteArray(), "ISO8859_1");
604             assertTrue("invalid conversion 3: " + converted, converted
605                     .equals("\u001b$B$(\u001b(B"));
606
607             bout.reset();
608             writer = new OutputStreamWriter(bout, "ISO2022JP");
609             writer.write(new char[] { '\u3048' });
610             writer.write(new char[] { '\u3048' });
611             writer.close();
612             // there should not be a mode switch between writes
613             assertEquals("invalid conversion 4", "\u001b$B$($(\u001b(B",
614                     new String(bout.toByteArray(), "ISO8859_1"));
615         } catch (UnsupportedEncodingException e) {
616             // Can't test missing converter
617             System.out.println(e);
618         }
619     }
620
621     /**
622      * @tests java.io.OutputStreamWriter#flush()
623      */
624     public void test_flush() throws IOException {
625         char[] buf = new char[testString.length()];
626         osw.write(testString, 0, testString.length());
627         osw.flush();
628         openInputStream();
629         isr.read(buf, 0, buf.length);
630         assertTrue("Chars not flushed", new String(buf, 0, buf.length)
631                 .equals(testString));
632     }
633
634     /**
635      * @tests java.io.OutputStreamWriter#getEncoding()
636      */
637     public void test_getEncoding() throws IOException {
638         try {
639             osw = new OutputStreamWriter(fos, "8859_1");
640         } catch (UnsupportedEncodingException e) {
641             assertEquals("Returned incorrect encoding", "8859_1", osw
642                     .getEncoding());
643         }
644
645         OutputStreamWriter out = new OutputStreamWriter(
646                 new ByteArrayOutputStream(), "UTF-16BE");
647         out.close();
648
649         String result = out.getEncoding();
650         assertNull(result);
651
652         out = null;
653         try {
654             out = new OutputStreamWriter(new ByteArrayOutputStream(),
655                     "UTF-16BE");
656         } catch (UnsupportedEncodingException e) {
657             // ok
658         }
659         result = out.getEncoding();
660         assertEquals("UnicodeBigUnmarked", result);
661     }
662
663     /**
664      * @tests java.io.OutputStreamWriter#write(char[], int, int)
665      */
666     public void test_write$CII() throws IOException {
667         char[] buf = new char[testString.length()];
668         osw.write(testString, 0, testString.length());
669         osw.close();
670         openInputStream();
671         isr.read(buf, 0, buf.length);
672         assertTrue("Incorrect chars returned", new String(buf, 0, buf.length)
673                 .equals(testString));
674     }
675
676     /**
677      * @tests java.io.OutputStreamWriter#write(int)
678      */
679     public void test_writeI() throws IOException {
680         osw.write('T');
681         osw.close();
682         openInputStream();
683         int c = isr.read();
684         assertEquals("Incorrect char returned", 'T', (char) c);
685     }
686
687     /**
688      * @tests java.io.OutputStreamWriter#write(java.lang.String, int, int)
689      */
690     public void test_writeLjava_lang_StringII() throws IOException {
691         char[] buf = new char[testString.length()];
692         osw.write(testString, 0, testString.length());
693         osw.close();
694         openInputStream();
695         isr.read(buf);
696         assertTrue("Incorrect chars returned", new String(buf, 0, buf.length)
697                 .equals(testString));
698     }
699
700     private void openInputStream() {
701         isr = new InputStreamReader(new ByteArrayInputStream(fos.toByteArray()));
702     }
703 }