View Javadoc
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  package org.apache.commons.io.testtools;
18  
19  import java.io.BufferedOutputStream;
20  import java.io.File;
21  import java.io.FileOutputStream;
22  import java.io.IOException;
23  import java.io.InputStream;
24  import java.io.OutputStream;
25  import java.io.OutputStreamWriter;
26  import java.io.PrintWriter;
27  import java.io.Reader;
28  import java.io.Writer;
29  import java.util.Arrays;
30  
31  import junit.framework.AssertionFailedError;
32  import junit.framework.TestCase;
33  
34  import org.apache.commons.io.FileUtils;
35  import org.apache.commons.io.IOUtils;
36  import org.apache.commons.io.output.ByteArrayOutputStream;
37  
38  /**
39   * Base class for testcases doing tests with files.
40   */
41  public abstract class FileBasedTestCase extends TestCase {
42  
43      private static volatile File testDir;
44  
45      public FileBasedTestCase(final String name) {
46          super(name);
47      }
48  
49      public static File getTestDirectory() {
50          if (testDir == null) {
51              testDir = new File("test/io/").getAbsoluteFile();
52          }
53          testDir.mkdirs();
54          return testDir;
55      }
56  
57      protected void createFile(final File file, final long size)
58              throws IOException {
59          if (!file.getParentFile().exists()) {
60              throw new IOException("Cannot create file " + file
61                  + " as the parent directory does not exist");
62          }
63          final BufferedOutputStream output =
64              new BufferedOutputStream(new java.io.FileOutputStream(file));
65          try {
66              generateTestData(output, size);
67          } finally {
68              IOUtils.closeQuietly(output);
69          }
70      }
71  
72      protected byte[] generateTestData(final long size) {
73          try {
74              final ByteArrayOutputStream baout = new ByteArrayOutputStream();
75              generateTestData(baout, size);
76              return baout.toByteArray();
77          } catch (final IOException ioe) {
78              throw new RuntimeException("This should never happen: " + ioe.getMessage());
79          }
80      }
81  
82      protected void generateTestData(final OutputStream out, final long size)
83                  throws IOException {
84          for (int i = 0; i < size; i++) {
85              //output.write((byte)'X');
86  
87              // nice varied byte pattern compatible with Readers and Writers
88              out.write( (byte)( (i % 127) + 1) );
89          }
90      }
91  
92      protected void createLineBasedFile(final File file, final String[] data) throws IOException {
93          if (file.getParentFile() != null && !file.getParentFile().exists()) {
94              throw new IOException("Cannot create file " + file + " as the parent directory does not exist");
95          }
96          final PrintWriter output = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
97          try {
98              for (final String element : data) {
99                  output.println(element);
100             }
101         } finally {
102             IOUtils.closeQuietly(output);
103         }
104     }
105 
106     protected File newFile(final String filename) throws IOException {
107         final File destination = new File( getTestDirectory(), filename );
108         /*
109         assertTrue( filename + "Test output data file shouldn't previously exist",
110                     !destination.exists() );
111         */
112         if (destination.exists()) {
113             FileUtils.forceDelete(destination);
114         }
115         return destination;
116     }
117 
118     protected void checkFile( final File file, final File referenceFile )
119                 throws Exception {
120         assertTrue( "Check existence of output file", file.exists() );
121         assertEqualContent( referenceFile, file );
122     }
123 
124     /** Assert that the content of two files is the same. */
125     private void assertEqualContent( final File f0, final File f1 )
126         throws IOException
127     {
128         /* This doesn't work because the filesize isn't updated until the file
129          * is closed.
130         assertTrue( "The files " + f0 + " and " + f1 +
131                     " have differing file sizes (" + f0.length() +
132                     " vs " + f1.length() + ")", ( f0.length() == f1.length() ) );
133         */
134         final InputStream is0 = new java.io.FileInputStream( f0 );
135         try {
136             final InputStream is1 = new java.io.FileInputStream( f1 );
137             try {
138                 final byte[] buf0 = new byte[ 1024 ];
139                 final byte[] buf1 = new byte[ 1024 ];
140                 int n0 = 0;
141                 int n1 = 0;
142 
143                 while( -1 != n0 )
144                 {
145                     n0 = is0.read( buf0 );
146                     n1 = is1.read( buf1 );
147                     assertTrue( "The files " + f0 + " and " + f1 +
148                                 " have differing number of bytes available (" + n0 +
149                                 " vs " + n1 + ")", ( n0 == n1 ) );
150 
151                     assertTrue( "The files " + f0 + " and " + f1 +
152                                 " have different content", Arrays.equals( buf0, buf1 ) );
153                 }
154             } finally {
155                 is1.close();
156             }
157         } finally {
158             is0.close();
159         }
160     }
161 
162     /** Assert that the content of a file is equal to that in a byte[]. */
163     protected void assertEqualContent(final byte[] b0, final File file) throws IOException {
164         final InputStream is = new java.io.FileInputStream(file);
165         int count = 0, numRead = 0;
166         final byte[] b1 = new byte[b0.length];
167         try {
168             while (count < b0.length && numRead >= 0) {
169                 numRead = is.read(b1, count, b0.length);
170                 count += numRead;
171             }
172             assertEquals("Different number of bytes: ", b0.length, count);
173             for (int i = 0; i < count; i++) {
174                 assertEquals("byte " + i + " differs", b0[i], b1[i]);
175             }
176         } finally {
177             is.close();
178         }
179     }
180 
181     /** Assert that the content of a file is equal to that in a char[]. */
182     protected void assertEqualContent(final char[] c0, final File file) throws IOException {
183         final Reader ir = new java.io.FileReader(file);
184         int count = 0, numRead = 0;
185         final char[] c1 = new char[c0.length];
186         try {
187             while (count < c0.length && numRead >= 0) {
188                 numRead = ir.read(c1, count, c0.length);
189                 count += numRead;
190             }
191             assertEquals("Different number of chars: ", c0.length, count);
192             for (int i = 0; i < count; i++) {
193                 assertEquals("char " + i + " differs", c0[i], c1[i]);
194             }
195         } finally {
196             ir.close();
197         }
198     }
199 
200     protected void checkWrite(final OutputStream output) throws Exception {
201         try {
202             new java.io.PrintStream(output).write(0);
203         } catch (final Throwable t) {
204             throw new AssertionFailedError(
205                 "The copy() method closed the stream "
206                     + "when it shouldn't have. "
207                     + t.getMessage());
208         }
209     }
210 
211     protected void checkWrite(final Writer output) throws Exception {
212         try {
213             new java.io.PrintWriter(output).write('a');
214         } catch (final Throwable t) {
215             throw new AssertionFailedError(
216                 "The copy() method closed the stream "
217                     + "when it shouldn't have. "
218                     + t.getMessage());
219         }
220     }
221 
222     protected void deleteFile( final File file )
223         throws Exception {
224         if (file.exists()) {
225             assertTrue("Couldn't delete file: " + file, file.delete());
226         }
227     }
228 
229 
230 }