View Javadoc
1   package org.codehaus.plexus.util;
2   
3   /*
4    * Copyright The Codehaus Foundation.
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  import java.io.BufferedOutputStream;
20  import java.io.ByteArrayOutputStream;
21  import java.io.File;
22  import java.io.FileInputStream;
23  import java.io.FileOutputStream;
24  import java.io.IOException;
25  import java.io.InputStream;
26  import java.io.OutputStream;
27  import java.io.PrintStream;
28  import java.io.PrintWriter;
29  import java.io.Writer;
30  import java.util.Arrays;
31  
32  import junit.framework.AssertionFailedError;
33  import junit.framework.TestCase;
34  
35  /**
36   * Base class for testcases doing tests with files.
37   *
38   * @author Jeremias Maerki
39   */
40  public abstract class FileBasedTestCase
41      extends TestCase
42  {
43      private static File testDir;
44  
45      public static File getTestDirectory()
46      {
47          if ( testDir == null )
48          {
49              testDir = ( new File( "target/test/io/" ) ).getAbsoluteFile();
50          }
51          return testDir;
52      }
53  
54      protected byte[] createFile( final File file, final long size )
55          throws IOException
56      {
57          if ( !file.getParentFile().exists() )
58          {
59              throw new IOException( "Cannot create file " + file + " as the parent directory does not exist" );
60          }
61  
62          byte[] data = generateTestData( size );
63  
64          final BufferedOutputStream output = new BufferedOutputStream( new FileOutputStream( file ) );
65  
66          try
67          {
68              output.write( data );
69  
70              return data;
71          }
72          finally
73          {
74              output.close();
75          }
76      }
77  
78      protected boolean createSymlink( final File link, final File target )
79      {
80          try
81          {
82              String[] args = { "ln", "-s", target.getAbsolutePath(), link.getAbsolutePath() };
83              Process process = Runtime.getRuntime().exec( args );
84              process.waitFor();
85              if ( 0 != process.exitValue() )
86              {
87                  return false;
88              }
89          }
90          catch ( Exception e )
91          {
92              // assume platform does not support "ln" command, tests should be skipped
93              return false;
94          }
95          return true;
96      }
97  
98      protected byte[] generateTestData( final long size )
99      {
100         try
101         {
102             ByteArrayOutputStream baout = new ByteArrayOutputStream();
103             generateTestData( baout, size );
104             return baout.toByteArray();
105         }
106         catch ( IOException ioe )
107         {
108             throw new RuntimeException( "This should never happen: " + ioe.getMessage() );
109         }
110     }
111 
112     protected void generateTestData( final OutputStream out, final long size )
113         throws IOException
114     {
115         for ( int i = 0; i < size; i++ )
116         {
117             // output.write((byte)'X');
118 
119             // nice varied byte pattern compatible with Readers and Writers
120             out.write( (byte) ( ( i % 127 ) + 1 ) );
121         }
122     }
123 
124     protected File newFile( String filename )
125         throws IOException
126     {
127         final File destination = new File( getTestDirectory(), filename );
128         /*
129          * assertTrue( filename + "Test output data file shouldn't previously exist", !destination.exists() );
130          */
131         if ( destination.exists() )
132         {
133             FileUtils.forceDelete( destination );
134         }
135         return destination;
136     }
137 
138     protected void checkFile( final File file, final File referenceFile )
139         throws Exception
140     {
141         assertTrue( "Check existence of output file", file.exists() );
142         assertEqualContent( referenceFile, file );
143     }
144 
145     protected void checkWrite( final OutputStream output )
146         throws Exception
147     {
148         try
149         {
150             new PrintStream( output ).write( 0 );
151         }
152         catch ( final Throwable t )
153         {
154             throw new AssertionFailedError( "The copy() method closed the stream " + "when it shouldn't have. "
155                 + t.getMessage() );
156         }
157     }
158 
159     protected void checkWrite( final Writer output )
160         throws Exception
161     {
162         try
163         {
164             new PrintWriter( output ).write( 'a' );
165         }
166         catch ( final Throwable t )
167         {
168             throw new AssertionFailedError( "The copy() method closed the stream " + "when it shouldn't have. "
169                 + t.getMessage() );
170         }
171     }
172 
173     protected void deleteFile( final File file )
174         throws Exception
175     {
176         if ( file.exists() )
177         {
178             assertTrue( "Couldn't delete file: " + file, file.delete() );
179         }
180     }
181 
182     // ----------------------------------------------------------------------
183     // Assertions
184     // ----------------------------------------------------------------------
185 
186     /** Assert that the content of two files is the same. */
187     private void assertEqualContent( final File f0, final File f1 )
188         throws IOException
189     {
190         /*
191          * This doesn't work because the filesize isn't updated until the file is closed. assertTrue( "The files " + f0
192          * + " and " + f1 + " have differing file sizes (" + f0.length() + " vs " + f1.length() + ")", ( f0.length() ==
193          * f1.length() ) );
194          */
195         final InputStream is0 = new FileInputStream( f0 );
196         try
197         {
198             final InputStream is1 = new FileInputStream( f1 );
199             try
200             {
201                 final byte[] buf0 = new byte[1024];
202                 final byte[] buf1 = new byte[1024];
203                 int n0 = 0;
204                 int n1 = 0;
205 
206                 while ( -1 != n0 )
207                 {
208                     n0 = is0.read( buf0 );
209                     n1 = is1.read( buf1 );
210                     assertTrue( "The files " + f0 + " and " + f1 + " have differing number of bytes available (" + n0
211                         + " vs " + n1 + ")", ( n0 == n1 ) );
212 
213                     assertTrue( "The files " + f0 + " and " + f1 + " have different content",
214                                 Arrays.equals( buf0, buf1 ) );
215                 }
216             }
217             finally
218             {
219                 is1.close();
220             }
221         }
222         finally
223         {
224             is0.close();
225         }
226     }
227 
228     /** Assert that the content of a file is equal to that in a byte[]. */
229     protected void assertEqualContent( final byte[] b0, final File file )
230         throws IOException
231     {
232         final InputStream is = new FileInputStream( file );
233         try
234         {
235             byte[] b1 = new byte[b0.length];
236             int numRead = is.read( b1 );
237             assertTrue( "Different number of bytes", numRead == b0.length && is.available() == 0 );
238             for ( int i = 0; i < numRead; assertTrue( "Byte " + i + " differs (" + b0[i] + " != " + b1[i] + ")",
239                                                       b0[i] == b1[i] ), i++ )
240                 ;
241         }
242         finally
243         {
244             is.close();
245         }
246     }
247 
248     protected void assertIsDirectory( File file )
249     {
250         assertTrue( "The File doesn't exists: " + file.getAbsolutePath(), file.exists() );
251 
252         assertTrue( "The File isn't a directory: " + file.getAbsolutePath(), file.isDirectory() );
253     }
254 
255     protected void assertIsFile( File file )
256     {
257         assertTrue( "The File doesn't exists: " + file.getAbsolutePath(), file.exists() );
258 
259         assertTrue( "The File isn't a file: " + file.getAbsolutePath(), file.isFile() );
260     }
261 }