FileInputStreamTest.java revision f6c387128427e121477c1b32ad35cdcaa5101ba3
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 tests.api.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;
26import java.nio.channels.FileChannel;
27
28import tests.support.Support_PlatformFile;
29import dalvik.annotation.TestLevel;
30import dalvik.annotation.TestTargetClass;
31import dalvik.annotation.TestTargetNew;
32
33@TestTargetClass(
34        value = FileInputStream.class,
35        untestedMethods = {
36            @TestTargetNew(
37                    method = "finalize",
38                    args = {},
39                    level = TestLevel.NOT_FEASIBLE,
40                    notes = "Hard to test since it requires that the " +
41                            "garbage collector runs; add test later."
42            )
43        }
44)
45public class FileInputStreamTest extends junit.framework.TestCase {
46
47    public String fileName;
48
49    private FileInputStream is;
50
51    byte[] ibuf = new byte[4096];
52
53    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_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_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";
54
55    /**
56     * @tests FileInputStream#FileInputStream(File)
57     */
58    @TestTargetNew(
59        level = TestLevel.PARTIAL_COMPLETE,
60        method = "FileInputStream",
61        args = {File.class}
62    )
63    public void test_ConstructorLjava_io_File() {
64        // Test for method FileInputStream(File)
65        try {
66            File f = new File(fileName);
67            is = new FileInputStream(f);
68            is.close();
69        } catch (Exception e) {
70            fail("Failed to create FileInputStream : " + e.getMessage());
71        }
72        File f2 = new File("ImprobableFile.42");
73        try {
74            is = new FileInputStream(f2);
75            is.close();
76            f2.delete();
77            fail("FileNotFoundException expected.");
78        } catch (FileNotFoundException e) {
79            // Expected.
80        } catch (IOException e) {
81            fail("Unexpected IOException: " + e.getMessage());
82        }
83    }
84
85    /**
86     * @tests FileInputStream#FileInputStream(FileDescriptor)
87     */
88    @TestTargetNew(
89        level = TestLevel.PARTIAL_COMPLETE,
90        method = "FileInputStream",
91        args = {FileDescriptor.class}
92    )
93    public void test_ConstructorLjava_io_FileDescriptor() {
94        // Test for method FileInputStream(FileDescriptor)
95        try {
96            FileOutputStream fos = new FileOutputStream(fileName);
97            FileInputStream fis = new FileInputStream(fos.getFD());
98            fos.close();
99            fis.close();
100        } catch (Exception e) {
101            fail("Exception during constrcutor test: " + e.toString());
102        }
103        try {
104            FileInputStream fis = new FileInputStream((FileDescriptor) null);
105            fis.close();
106            fail("NullPointerException expected.");
107        } catch (NullPointerException e) {
108            // Expected.
109        } catch (IOException e) {
110            fail("Unexpected IOException: " + e.getMessage());
111        }
112    }
113
114    /**
115     * @tests FileInputStream#FileInputStream(java.lang.String)
116     */
117    @TestTargetNew(
118        level = TestLevel.PARTIAL_COMPLETE,
119        method = "FileInputStream",
120        args = {java.lang.String.class}
121    )
122    public void test_ConstructorLjava_lang_String() {
123        // Test for method FileInputStream(java.lang.String)
124        try {
125            is = new FileInputStream(fileName);
126            is.close();
127        } catch (Exception e) {
128            fail("Failed to create FileInputStream : " + e.getMessage());
129        }
130        try {
131            is = new FileInputStream("ImprobableFile.42");
132            is.close();
133            new File("ImprobableFile.42").delete();
134            fail("FileNotFoundException expected.");
135        } catch (FileNotFoundException e) {
136            // Expected.
137        } catch (IOException e) {
138            fail("Unexpected IOException: " + e.getMessage());
139        }
140    }
141
142    /**
143     * @tests FileInputStream#available()
144     */
145    @TestTargetNew(
146        level = TestLevel.COMPLETE,
147        method = "available",
148        args = {}
149    )
150    public void test_available() throws IOException {
151        is = new FileInputStream(fileName);
152        assertEquals("Test 1: Returned incorrect number of available bytes;",
153                fileString.length(), is.available());
154        is.close();
155        try {
156            is.available();
157            fail("Test 2: IOException expected.");
158        } catch (IOException e) {
159            // Expected.
160        }
161    }
162
163    /**
164     * @tests FileInputStream#close()
165     */
166    @TestTargetNew(
167        level = TestLevel.SUFFICIENT,
168        notes = "No IOException test since this is only thrown" +
169                "by a native method.",
170        method = "close",
171        args = {}
172    )
173    public void test_close() throws IOException {
174        is = new FileInputStream(fileName);
175        is.close();
176
177        try {
178            is.read();
179            fail("Test 1: Read from closed stream succeeded.");
180        } catch (IOException e) {
181            // Expected.
182        }
183    }
184
185    /**
186     * @tests FileInputStream#getChannel()
187     */
188    @TestTargetNew(
189        level = TestLevel.COMPLETE,
190        notes = "",
191        method = "getChannel",
192        args = {}
193    )
194    public void test_getChannel() {
195        // Test for method FileChannel FileInputStream.getChannel()
196        FileChannel channel;
197        byte[] buffer = new byte[100];
198        byte[] stringBytes;
199        final int offset = 5;
200        boolean equal = true;
201
202        try {
203            FileInputStream fis = new FileInputStream(fileName);
204            channel = fis.getChannel();
205            assertNotNull(channel);
206            assertTrue("Channel is closed.", channel.isOpen());
207
208            // Check that the channel is associated with the input stream.
209            channel.position(offset);
210            fis.read(buffer, 0, 10);
211            stringBytes = fileString.getBytes();
212            for (int i = 0; i < 10; i++) {
213                equal &= (buffer[i] == stringBytes[i + offset]);
214            }
215            assertTrue("Channel is not associated with this stream.", equal);
216
217            fis.close();
218            assertFalse("Channel has not been closed.", channel.isOpen());
219        } catch (FileNotFoundException e) {
220            fail("Could not find : " + fileName);
221        }
222
223        catch (IOException e) {
224            fail("Exception during test : " + e.getMessage());
225        }
226    }
227
228    /**
229     * @tests FileInputStream#getFD()
230     */
231    @TestTargetNew(
232        level = TestLevel.SUFFICIENT,
233        notes = "No IOException check since it is never thrown.",
234        method = "getFD",
235        args = {}
236    )
237    public void test_getFD() {
238        // Test for method FileDescriptor
239        // FileInputStream.getFD()
240        try {
241
242            FileInputStream fis = new FileInputStream(fileName);
243            assertTrue("Returned invalid fd", fis.getFD().valid());
244            fis.close();
245            assertTrue("Returned invalid fd", !fis.getFD().valid());
246        } catch (FileNotFoundException e) {
247            fail("Could not find : " + fileName);
248        }
249        catch (IOException e) {
250            fail("Exception during test : " + e.getMessage());
251        }
252    }
253
254    /**
255     * @tests FileInputStream#read()
256     */
257    @TestTargetNew(
258        level = TestLevel.COMPLETE,
259        method = "read",
260        args = {}
261    )
262    public void test_read() throws IOException {
263        is = new FileInputStream(fileName);
264        int c = is.read();
265        assertEquals("Test 1: Read returned incorrect char;",
266                fileString.charAt(0), c);
267
268        is.close();
269        try {
270            is.read();
271            fail("Test 2: IOException expected.");
272        } catch (IOException e) {
273            // Expected.
274        }
275    }
276
277    /**
278     * @tests FileInputStream#read(byte[])
279     */
280    @TestTargetNew(
281        level = TestLevel.COMPLETE,
282        method = "read",
283        args = {byte[].class}
284    )
285    public void test_read$B() throws IOException {
286        byte[] buf1 = new byte[100];
287        is = new FileInputStream(fileName);
288        is.skip(3000);
289        is.read(buf1);
290        is.close();
291        assertTrue("Test 1: Failed to read correct data.",
292                new String(buf1, 0, buf1.length).equals(
293                        fileString.substring(3000, 3100)));
294
295        is.close();
296        try {
297            is.read(buf1);
298            fail("Test 2: IOException expected.");
299        } catch (IOException e) {
300            // Expected.
301        }
302    }
303
304    /**
305     * @tests FileInputStream#read(byte[], int, int)
306     */
307    @TestTargetNew(
308        level = TestLevel.PARTIAL_COMPLETE,
309        method = "read",
310        args = {byte[].class, int.class, int.class}
311    )
312    public void test_read$BII() {
313        // Test for method int FileInputStream.read(byte [], int, int)
314        byte[] buf1 = new byte[100];
315        try {
316            is = new FileInputStream(fileName);
317            is.skip(3000);
318            is.read(buf1, 0, buf1.length);
319            is.close();
320            assertTrue("Failed to read correct data", new String(buf1, 0,
321                    buf1.length).equals(fileString.substring(3000, 3100)));
322
323        } catch (Exception e) {
324            fail("Exception during read test : " + e.getMessage());
325        }
326    }
327
328    /**
329     * @tests FileInputStream#read(byte[], int, int)
330     */
331    @TestTargetNew(
332        level = TestLevel.PARTIAL_COMPLETE,
333        notes = "Illegal argument checks.",
334        method = "read",
335        args = {byte[].class, int.class, int.class}
336    )
337    public void test_read$BII_Exception() throws IOException {
338        byte[] buf = null;
339        try {
340            is = new FileInputStream(fileName);
341            is.read(buf, 0, 0);
342            fail("Test 1: NullPointerException expected.");
343        } catch (NullPointerException e) {
344            // Expected.
345        } finally {
346            is.close();
347        }
348
349        buf = new byte[1000];
350        try {
351            is = new FileInputStream(fileName);
352            is.read(buf, -1, 0);
353            fail("Test 2: IndexOutOfBoundsException expected.");
354        } catch (IndexOutOfBoundsException e) {
355            // Expected.
356        } finally {
357            is.close();
358        }
359
360        try {
361            is = new FileInputStream(fileName);
362            is.read(buf, 0, -1);
363            fail("Test 3: IndexOutOfBoundsException expected.");
364        } catch (IndexOutOfBoundsException e) {
365            // Expected.
366        } finally {
367            is.close();
368        }
369
370        try {
371            is = new FileInputStream(fileName);
372            is.read(buf, -1, -1);
373            fail("Test 4: IndexOutOfBoundsException expected.");
374        } catch (IndexOutOfBoundsException e) {
375            // Expected.
376        } finally {
377            is.close();
378        }
379
380        try {
381            is = new FileInputStream(fileName);
382            is.read(buf, 0, 1001);
383            fail("Test 5: IndexOutOfBoundsException expected.");
384        } catch (IndexOutOfBoundsException e) {
385            // Expected.
386        } finally {
387            is.close();
388        }
389
390        try {
391            is = new FileInputStream(fileName);
392            is.read(buf, 1001, 0);
393            fail("Test 6: IndexOutOfBoundsException expected.");
394        } catch (IndexOutOfBoundsException e) {
395            // Expected.
396        } finally {
397            is.close();
398        }
399
400        try {
401            is = new FileInputStream(fileName);
402            is.read(buf, 500, 501);
403            fail("Test 7: IndexOutOfBoundsException expected.");
404        } catch (IndexOutOfBoundsException e) {
405            // Expected.
406        } finally {
407            is.close();
408        }
409
410        try {
411            is = new FileInputStream(fileName);
412            is.close();
413            is.read(buf, 0, 100);
414            fail("Test 8: IOException expected.");
415        } catch (IOException e) {
416            // Expected.
417        } finally {
418            is.close();
419        }
420    }
421
422    /**
423     * @tests FileInputStream#skip(long)
424     */
425    @TestTargetNew(
426        level = TestLevel.PARTIAL_COMPLETE,
427        method = "skip",
428        args = {long.class}
429    )
430    public void test_skipJ() throws IOException {
431        byte[] buf1 = new byte[10];
432        is = new FileInputStream(fileName);
433        is.skip(1000);
434        is.read(buf1, 0, buf1.length);
435        assertTrue("Test 1: Failed to skip to correct position.",
436                new String(buf1, 0, buf1.length).equals(
437                        fileString.substring(1000, 1010)));
438
439        is.close();
440        try {
441            is.read();
442            fail("Test 2: IOException expected.");
443        } catch (IOException e) {
444            // Expected.
445        }
446    }
447
448    /**
449     * @tests FileInputStream#skip(long)
450     */
451    @TestTargetNew(
452        level = TestLevel.PARTIAL_COMPLETE,
453        notes = "Verifies that skip(long) method throws IOException if " +
454                "this method is called with negative argument.",
455        method = "skip",
456        args = {long.class}
457    )
458    public void test_skipNegativeArgumentJ() throws IOException{
459
460        FileInputStream fis = new FileInputStream(fileName);
461
462        try {
463            fis.skip(-5);
464            fail("Test 1: IOException expected.");
465        } catch (IOException e) {
466            // Expected IOException
467        } catch (Exception e) {
468            fail("Test 2: IOException expected but found: " + e.getMessage());
469        }
470
471        fis.close();
472    }
473
474    /**
475     * Sets up the fixture, for example, open a network connection. This method
476     * is called before a test is executed.
477     */
478    protected void setUp() {
479        try {
480            fileName = System.getProperty("java.io.tmpdir");
481            String separator = System.getProperty("file.separator");
482            if (fileName.charAt(fileName.length() - 1) == separator.charAt(0))
483                fileName = Support_PlatformFile.getNewPlatformFile(fileName,
484                        "input.tst");
485            else
486                fileName = Support_PlatformFile.getNewPlatformFile(fileName
487                        + separator, "input.tst");
488            java.io.OutputStream fos = new FileOutputStream(fileName);
489            fos.write(fileString.getBytes());
490            fos.close();
491        } catch (java.io.IOException e) {
492            System.out.println("Exception during setup");
493            e.printStackTrace();
494        }
495    }
496
497    /**
498     * Tears down the fixture, for example, close a network connection. This
499     * method is called after a test is executed.
500     */
501    protected void tearDown() {
502        try {
503            if (is != null) {
504                is.close();
505            }
506            new File(fileName).delete();
507        } catch (IOException e) {
508            // Ignored.
509        }
510    }
511}
512