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, WITHOUT
13 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 * License for the specific language governing permissions and limitations under
15 * the License.
16 */
17
18package org.apache.harmony.tests.java.io;
19
20import java.io.File;
21import java.io.FileDescriptor;
22import java.io.FileInputStream;
23import java.io.FileNotFoundException;
24import java.io.FileOutputStream;
25import java.io.IOException;
26
27import junit.framework.TestCase;
28
29public class FileOutputStreamTest extends TestCase {
30
31    private FileOutputStream fos;
32    private FileInputStream fis;
33    private File f;
34    private byte[] bytes;
35
36    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_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n";
37
38    protected void setUp() {
39        bytes = new byte[10];
40        for (int i = 0; i < bytes.length; i++) {
41            bytes[i] = (byte) i;
42        }
43    }
44
45    /**
46     * Tears down the fixture, for example, close a network connection. This
47     * method is called after a test is executed.
48     */
49    @Override
50    protected void tearDown() throws Exception {
51        super.tearDown();
52        if (f != null) {
53            f.delete();
54        }
55        if (fis != null) {
56            fis.close();
57        }
58        if (fos != null) {
59            fos.close();
60        }
61    }
62
63    /**
64     * java.io.FileOutputStream#FileOutputStream(java.io.File)
65     */
66    public void test_ConstructorLjava_io_File() throws IOException {
67        f = File.createTempFile("FileOutputStreamTest", "tst");
68        fos = new FileOutputStream(f);
69    }
70
71    /**
72     * java.io.FileOutputStream#FileOutputStream(java.io.FileDescriptor)
73     */
74    public void test_ConstructorLjava_io_FileDescriptor() throws IOException {
75        f = File.createTempFile("FileOutputStreamTest", "tst");
76        String fileName = f.getAbsolutePath();
77        fos = new FileOutputStream(fileName);
78        fos.write('l');
79        fos.close();
80        fis = new FileInputStream(fileName);
81        fos = new FileOutputStream(fis.getFD());
82        fos.close();
83        fis.close();
84    }
85
86    /**
87     * java.io.FileOutputStream#FileOutputStream(java.lang.String)
88     */
89    public void test_ConstructorLjava_lang_String() throws IOException {
90        f = File.createTempFile("FileOutputStreamTest", "tst");
91        String fileName = f.getAbsolutePath();
92        fos = new FileOutputStream(fileName);
93
94        // Harmony 4012.
95        fos = new FileOutputStream("/dev/null");
96        fos.close();
97    }
98
99    /**
100     * java.io.FileOutputStream#FileOutputStream(java.lang.String,
101     *boolean)
102     */
103    public void test_ConstructorLjava_lang_StringZ() throws IOException {
104        f = File.createTempFile("FileOutputStreamTest", "tst");
105        fos = new FileOutputStream(f.getPath(), false);
106        fos.write("HI".getBytes(), 0, 2);
107        fos.close();
108        fos = new FileOutputStream(f.getPath(), true);
109        fos.write(fileString.getBytes());
110        fos.close();
111        byte[] buf = new byte[fileString.length() + 2];
112        fis = new FileInputStream(f.getPath());
113        fis.read(buf, 0, buf.length);
114        assertTrue("Failed to create appending stream", new String(buf, 0,
115                buf.length).equals("HI" + fileString));
116    }
117
118    /**
119     * java.io.FileOutputStream#FileOutputStream(java.lang.String)
120     */
121    public void test_ConstructorLjava_lang_String_I() throws IOException {
122        try {
123            fos = new FileOutputStream("");
124            fail("should throw FileNotFoundException.");
125        } catch (FileNotFoundException e) {
126            // Expected
127        } finally {
128            if (fos != null) {
129                fos.close();
130            }
131        }
132        try {
133            fos = new FileOutputStream(new File(""));
134            fail("should throw FileNotFoundException.");
135        } catch (FileNotFoundException e) {
136            // Expected
137        } finally {
138            if (fos != null) {
139                fos.close();
140            }
141        }
142    }
143
144    /**
145     * java.io.FileOutputStream#close()
146     */
147    public void test_close() throws IOException {
148        f = File.createTempFile("FileOutputStreamTest", "tst");
149        fos = new FileOutputStream(f.getPath());
150        fos.close();
151
152        try {
153            fos.write(fileString.getBytes());
154            fail("Close test failed - wrote to closed stream");
155        } catch (IOException e) {
156            // Expected
157        }
158    }
159
160    /**
161     * java.io.FileOutputStream#getFD()
162     */
163    public void test_getFD() throws IOException {
164        f = File.createTempFile("FileOutputStreamTest", "tst");
165        String fileName = f.getAbsolutePath();
166        fos = new FileOutputStream(f);
167        assertTrue("Returned invalid fd", fos.getFD().valid());
168        fos.close();
169        assertTrue("Returned invalid fd", !fos.getFD().valid());
170    }
171
172    /**
173     * java.io.FileOutputStream#write(byte[])
174     */
175    public void test_write$B() throws IOException {
176        f = File.createTempFile("FileOutputStreamTest", "tst");
177        fos = new FileOutputStream(f.getPath());
178        fos.write(fileString.getBytes());
179        fis = new FileInputStream(f.getPath());
180        byte rbytes[] = new byte[4000];
181        fis.read(rbytes, 0, fileString.length());
182        assertTrue("Incorrect string returned", new String(rbytes, 0,
183                fileString.length()).equals(fileString));
184    }
185
186    /**
187     * java.io.FileOutputStream#write(byte[], int, int)
188     */
189    public void test_write$BII() throws IOException {
190        f = File.createTempFile("FileOutputStreamTest", "tst");
191        fos = new FileOutputStream(f.getPath());
192        fos.write(fileString.getBytes(), 0, fileString.length());
193        fis = new FileInputStream(f.getPath());
194        byte rbytes[] = new byte[4000];
195        fis.read(rbytes, 0, fileString.length());
196        assertTrue("Incorrect bytes written", new String(rbytes, 0, fileString
197                .length()).equals(fileString));
198
199        // Regression test for HARMONY-285
200        File file = File.createTempFile("FileOutputStreamTest", ".tmp");
201        FileOutputStream out = new FileOutputStream(file);
202        try {
203            out.write(null, 0, 0);
204            fail();
205        } catch (NullPointerException expected) {
206
207        } finally {
208            out.close();
209            file.delete();
210        }
211    }
212
213    /**
214     * java.io.FileOutputStream#write(int)
215     */
216    public void test_writeI() throws IOException {
217        f = File.createTempFile("FileOutputStreamTest", "tst");
218        fos = new FileOutputStream(f.getPath());
219        fos.write('t');
220        fis = new FileInputStream(f.getPath());
221        assertEquals("Incorrect char written", 't', fis.read());
222    }
223
224    /**
225     * java.io.FileOutputStream#write(byte[], int, int)
226     */
227    public void test_write$BII2() throws IOException {
228        // Regression for HARMONY-437
229        f = File.createTempFile("FileOutputStreamTest", "tst");
230        fos = new FileOutputStream(f.getPath());
231
232        try {
233            fos.write(null, 1, 1);
234            fail("NullPointerException must be thrown");
235        } catch (NullPointerException e) {
236        }
237
238        try {
239            fos.write(new byte[1], -1, 1);
240            fail("IndexOutOfBoundsException must be thrown if off <0");
241        } catch (IndexOutOfBoundsException e) {
242        }
243
244        try {
245            fos.write(new byte[1], 0, -1);
246            fail("IndexOutOfBoundsException must be thrown if len <0");
247        } catch (IndexOutOfBoundsException e) {
248        }
249
250        try {
251            fos.write(new byte[1], 0, 5);
252            fail("IndexOutOfBoundsException must be thrown if off+len > b.length");
253        } catch (IndexOutOfBoundsException e) {
254        }
255
256        try {
257            fos.write(new byte[10], Integer.MAX_VALUE, 5);
258            fail("IndexOutOfBoundsException expected");
259        } catch (IndexOutOfBoundsException e) {
260        }
261
262        try {
263            fos.write(new byte[10], 5, Integer.MAX_VALUE);
264            fail("IndexOutOfBoundsException expected");
265        } catch (IndexOutOfBoundsException e) {
266        }
267        fos.close();
268    }
269
270    /**
271     * java.io.FileOutputStream#write(byte[], int, int)
272     */
273    public void test_write$BII3() throws IOException {
274        // Regression for HARMONY-834
275        // no exception expected
276        new FileOutputStream(new FileDescriptor()).write(new byte[1], 0, 0);
277    }
278
279    /**
280     * java.io.FileOutputStream#getChannel()
281     */
282    public void test_getChannel() throws IOException {
283        // Regression for HARMONY-508
284        File tmpfile = File.createTempFile("FileOutputStream", "tmp");
285        tmpfile.deleteOnExit();
286        FileOutputStream fos = new FileOutputStream(tmpfile);
287        fos.write(bytes);
288        fos.flush();
289        fos.close();
290        FileOutputStream f = new FileOutputStream(tmpfile, true);
291        // Harmony expected 10, but the RI and Android report 0.
292        assertEquals(0, f.getChannel().position());
293    }
294
295    public void test_getChannel_Append() throws IOException {
296        File tmpfile = File.createTempFile("FileOutputStream", "tmp");
297        tmpfile.deleteOnExit();
298        FileOutputStream fos = new FileOutputStream(tmpfile, true);
299        assertEquals(0, fos.getChannel().position());
300        fos.write(bytes);
301        assertEquals(10, fos.getChannel().position());
302        fos.write(bytes);
303        assertEquals(20, fos.getChannel().position());
304        fos.write(bytes);
305        assertEquals(30, fos.getChannel().position());
306        fos.close();
307
308        try {
309            fos.getChannel().position();
310            fail("should throw ClosedChannelException");
311        } catch (java.nio.channels.ClosedChannelException e) {
312            // Expected
313        }
314    }
315
316    public void test_getChannel_UnAppend() throws IOException {
317        File tmpfile = File.createTempFile("FileOutputStream", "tmp");
318        tmpfile.deleteOnExit();
319        FileOutputStream fos = new FileOutputStream(tmpfile, false);
320        assertEquals(0, fos.getChannel().position());
321        fos.write(bytes);
322        assertEquals(10, fos.getChannel().position());
323        fos.write(bytes);
324        assertEquals(20, fos.getChannel().position());
325        fos.write(bytes);
326        assertEquals(30, fos.getChannel().position());
327        fos.close();
328
329        try {
330            fos.getChannel().position();
331            fail("should throw ClosedChannelException");
332        } catch (java.nio.channels.ClosedChannelException e) {
333            // Expected
334        }
335    }
336
337    public void test_getChannel_Unappend_Unappend() throws IOException {
338        File tmpfile = File.createTempFile("FileOutputStream", "tmp");
339        tmpfile.deleteOnExit();
340        FileOutputStream fos = new FileOutputStream(tmpfile, false);
341        assertEquals(0, fos.getChannel().position());
342        fos.write(bytes);
343        assertEquals(10, fos.getChannel().position());
344        fos.close();
345
346        fos = new FileOutputStream(tmpfile, false);
347        assertEquals(0, fos.getChannel().position());
348        fos.close();
349    }
350
351    public void test_getChannel_Unappend_Append() throws IOException {
352        File tmpfile = File.createTempFile("FileOutputStream", "tmp");
353        tmpfile.deleteOnExit();
354        FileOutputStream fos = new FileOutputStream(tmpfile, false);
355        assertEquals(0, fos.getChannel().position());
356        fos.write(bytes);
357        assertEquals(10, fos.getChannel().position());
358        fos.close();
359
360        fos = new FileOutputStream(tmpfile, true);
361        // Harmony expected 10, but the RI and Android report 0.
362        assertEquals(0, fos.getChannel().position());
363        fos.close();
364    }
365
366    public void test_getChannel_Append_Unappend() throws IOException {
367        File tmpfile = File.createTempFile("FileOutputStream", "tmp");
368        tmpfile.deleteOnExit();
369        FileOutputStream fos = new FileOutputStream(tmpfile, true);
370        assertEquals(0, fos.getChannel().position());
371        fos.write(bytes);
372        assertEquals(10, fos.getChannel().position());
373        fos.close();
374
375        fos = new FileOutputStream(tmpfile, false);
376        assertEquals(0, fos.getChannel().position());
377        fos.close();
378    }
379
380    public void test_getChanne_Append_Append() throws IOException {
381        File tmpfile = File.createTempFile("FileOutputStream", "tmp");
382        tmpfile.deleteOnExit();
383        FileOutputStream fos = new FileOutputStream(tmpfile, true);
384        assertEquals(0, fos.getChannel().position());
385        fos.write(bytes);
386        assertEquals(10, fos.getChannel().position());
387        fos.close();
388
389        fos = new FileOutputStream(tmpfile, true);
390        // Harmony expected 10, but the RI and Android report 0.
391        assertEquals(0, fos.getChannel().position());
392        fos.close();
393    }
394}
395