KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > io > FileUtilsTestCase


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.commons.io;
17
18 import java.io.File JavaDoc;
19 import java.io.FileInputStream JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.io.OutputStream JavaDoc;
22 import java.net.URL JavaDoc;
23
24 import org.apache.commons.io.testtools.FileBasedTestCase;
25
26 import junit.framework.Test;
27 import junit.framework.TestSuite;
28 import junit.textui.TestRunner;
29
30 /**
31  * This is used to test FileUtils for correctness.
32  *
33  * @author Peter Donald
34  * @author Matthew Hawthorne
35  * @version $Id: FileUtilsTestCase.java,v 1.18 2004/04/23 22:47:39 jeremias Exp $
36  * @see FileUtils
37  */

38 public class FileUtilsTestCase extends FileBasedTestCase {
39
40     // Test data
41

42     /**
43      * Size of test directory.
44      */

45     private static final int TEST_DIRECTORY_SIZE = 0;
46     
47     /** Delay in milliseconds to make sure test for "last modified date" are accurate */
48     private static final int LAST_MODIFIED_DELAY = 600;
49
50     private File JavaDoc testFile1;
51     private File JavaDoc testFile2;
52
53     private static int testFile1Size;
54     private static int testFile2Size;
55
56     public static void main(String JavaDoc[] args) {
57         TestRunner.run(suite());
58     }
59
60     public static Test suite() {
61         return new TestSuite(FileUtilsTestCase.class);
62     }
63
64     public FileUtilsTestCase(String JavaDoc name) throws IOException JavaDoc {
65         super(name);
66
67         testFile1 = new File JavaDoc(getTestDirectory(), "file1-test.txt");
68         testFile2 = new File JavaDoc(getTestDirectory(), "file1a-test.txt");
69
70         testFile1Size = (int)testFile1.length();
71         testFile2Size = (int)testFile2.length();
72     }
73
74     /** @see junit.framework.TestCase#setUp() */
75     protected void setUp() throws Exception JavaDoc {
76         getTestDirectory().mkdirs();
77         createFile(testFile1, testFile1Size);
78         createFile(testFile2, testFile2Size);
79         FileUtils.deleteDirectory(getTestDirectory());
80         getTestDirectory().mkdirs();
81         createFile(testFile1, testFile1Size);
82         createFile(testFile2, testFile2Size);
83     }
84
85     /** @see junit.framework.TestCase#tearDown() */
86     protected void tearDown() throws Exception JavaDoc {
87         FileUtils.deleteDirectory(getTestDirectory());
88     }
89
90     // byteCountToDisplaySize
91

92     public void testByteCountToDisplaySize() {
93         assertEquals(FileUtils.byteCountToDisplaySize(0), "0 bytes");
94         assertEquals(FileUtils.byteCountToDisplaySize(1024), "1 KB");
95         assertEquals(FileUtils.byteCountToDisplaySize(1024 * 1024), "1 MB");
96         assertEquals(
97             FileUtils.byteCountToDisplaySize(1024 * 1024 * 1024),
98             "1 GB");
99     }
100
101     // waitFor
102

103     public void testWaitFor() {
104         FileUtils.waitFor(new File JavaDoc(""), -1);
105
106         FileUtils.waitFor(new File JavaDoc(""), 2);
107     }
108
109     // toURL
110

111     public void testToURLs() throws Exception JavaDoc {
112         File JavaDoc[] files = new File JavaDoc[] { new File JavaDoc("file1"), new File JavaDoc("file2")};
113
114         URL JavaDoc[] urls = FileUtils.toURLs(files);
115
116         // Path separator causes equality tests to fail
117
//assertEquals(urls[0].getFile(), File.separator + files[0].getAbsolutePath());
118
//assertEquals(urls[1].getFile(), File.separator + files[1].getAbsolutePath());
119

120     }
121
122     // contentEquals
123

124     public void testContentEquals() throws Exception JavaDoc {
125         // Non-existent files
126
File JavaDoc file = new File JavaDoc(getTestDirectory(), getName());
127         assertTrue(FileUtils.contentEquals(file, file));
128
129         // Directories
130
try {
131             FileUtils.contentEquals(getTestDirectory(), getTestDirectory());
132             fail("Comparing directories should fail with an IOException");
133         } catch (IOException JavaDoc ioe) {
134             //expected
135
}
136
137         // Different files
138
File JavaDoc objFile1 =
139             new File JavaDoc(getTestDirectory(), getName() + ".object");
140         objFile1.deleteOnExit();
141         FileUtils.copyURLToFile(
142             getClass().getResource("/java/lang/Object.class"),
143             objFile1);
144
145         File JavaDoc objFile2 =
146             new File JavaDoc(getTestDirectory(), getName() + ".collection");
147         objFile2.deleteOnExit();
148         FileUtils.copyURLToFile(
149             getClass().getResource("/java/util/Collection.class"),
150             objFile2);
151
152         assertTrue(
153             "Files should not be equal.",
154             !FileUtils.contentEquals(objFile1, objFile2));
155
156         // Equal files
157
file.createNewFile();
158         assertTrue(FileUtils.contentEquals(file, file));
159     }
160
161     // copyURLToFile
162

163     public void testCopyURLToFile() throws Exception JavaDoc {
164         // Creates file
165
File JavaDoc file = new File JavaDoc(getTestDirectory(), getName());
166         file.deleteOnExit();
167
168         // Loads resource
169
String JavaDoc resourceName = "/java/lang/Object.class";
170         FileUtils.copyURLToFile(getClass().getResource(resourceName), file);
171
172         // Tests that resuorce was copied correctly
173
FileInputStream JavaDoc fis = new FileInputStream JavaDoc(file);
174         try {
175             assertTrue(
176                 "Content is not equal.",
177                 IOUtils.contentEquals(
178                     getClass().getResourceAsStream(resourceName),
179                     fis));
180         } finally {
181             fis.close();
182         }
183         //TODO Maybe test copy to itself like for copyFile()
184
}
185
186     // forceMkdir
187

188     public void testForceMkdir() throws Exception JavaDoc {
189         // Tests with existing directory
190
FileUtils.forceMkdir(getTestDirectory());
191
192         // Creates test file
193
File JavaDoc testFile = new File JavaDoc(getTestDirectory(), getName());
194         testFile.deleteOnExit();
195         testFile.createNewFile();
196         assertTrue("Test file does not exist.", testFile.exists());
197
198         // Tests with existing file
199
try {
200             FileUtils.forceMkdir(testFile);
201             fail("Exception expected.");
202         } catch (IOException JavaDoc ex) {}
203
204         testFile.delete();
205
206         // Tests with non-existent directory
207
FileUtils.forceMkdir(testFile);
208         assertTrue("Directory was not created.", testFile.exists());
209     }
210
211     // sizeOfDirectory
212

213     public void testSizeOfDirectory() throws Exception JavaDoc {
214         File JavaDoc file = new File JavaDoc(getTestDirectory(), getName());
215
216         // Non-existent file
217
try {
218             FileUtils.sizeOfDirectory(file);
219             fail("Exception expected.");
220         } catch (IllegalArgumentException JavaDoc ex) {}
221
222         // Creates file
223
file.createNewFile();
224         file.deleteOnExit();
225
226         // Existing file
227
try {
228             FileUtils.sizeOfDirectory(file);
229             fail("Exception expected.");
230         } catch (IllegalArgumentException JavaDoc ex) {}
231
232         // Existing directory
233
file.delete();
234         file.mkdir();
235
236         assertEquals(
237             "Unexpected directory size",
238             TEST_DIRECTORY_SIZE,
239             FileUtils.sizeOfDirectory(file));
240     }
241
242     // isFileNewer
243

244     // TODO Finish test
245
public void XtestIsFileNewer() {}
246
247     // TODO Remove after debugging
248
private void log(Object JavaDoc obj) {
249         System.out.println(
250             FileUtilsTestCase.class +" " + getName() + " " + obj);
251     }
252
253     // copyFile
254

255     public void testCopyFile1() throws Exception JavaDoc {
256         File JavaDoc destination = new File JavaDoc(getTestDirectory(), "copy1.txt");
257         
258         //Thread.sleep(LAST_MODIFIED_DELAY);
259
//This is to slow things down so we can catch if
260
//the lastModified date is not ok
261

262         FileUtils.copyFile(testFile1, destination);
263         assertTrue("Check Exist", destination.exists());
264         assertTrue("Check Full copy", destination.length() == testFile1Size);
265         /* disabled: Thread.sleep doesn't work reliantly for this case
266         assertTrue("Check last modified date preserved",
267             testFile1.lastModified() == destination.lastModified());*/

268     }
269
270     public void testCopyFile2() throws Exception JavaDoc {
271         File JavaDoc destination = new File JavaDoc(getTestDirectory(), "copy2.txt");
272         
273         Thread.sleep(LAST_MODIFIED_DELAY);
274         //This is to slow things down so we can catch if
275
//the lastModified date is not ok
276

277         FileUtils.copyFile(testFile1, destination);
278         assertTrue("Check Exist", destination.exists());
279         assertTrue("Check Full copy", destination.length() == testFile2Size);
280         assertTrue("Check last modified date preserved",
281             testFile1.lastModified() == destination.lastModified());
282     }
283     
284     public void testCopyToSelf() throws Exception JavaDoc {
285         File JavaDoc destination = new File JavaDoc(getTestDirectory(), "copy3.txt");
286         //Prepare a test file
287
FileUtils.copyFile(testFile1, destination);
288         
289         try {
290             FileUtils.copyFile(destination, destination);
291             fail("file copy to self should not be possible");
292         } catch (IOException JavaDoc ioe) {
293             //we want the exception, copy to self should be illegal
294
}
295     }
296
297     public void testCopyFile2WithoutFileDatePreservation() throws Exception JavaDoc {
298         File JavaDoc destination = new File JavaDoc(getTestDirectory(), "copy2.txt");
299         
300         //Thread.sleep(LAST_MODIFIED_DELAY);
301
//This is to slow things down so we can catch if
302
//the lastModified date is not ok
303

304         FileUtils.copyFile(testFile1, destination, false);
305         assertTrue("Check Exist", destination.exists());
306         assertTrue("Check Full copy", destination.length() == testFile2Size);
307         /* disabled: Thread.sleep doesn't work reliantly for this case
308         assertTrue("Check last modified date modified",
309             testFile1.lastModified() != destination.lastModified());*/

310     }
311
312     // forceDelete
313

314     public void testForceDeleteAFile1() throws Exception JavaDoc {
315         File JavaDoc destination = new File JavaDoc(getTestDirectory(), "copy1.txt");
316         destination.createNewFile();
317         assertTrue("Copy1.txt doesn't exist to delete", destination.exists());
318         FileUtils.forceDelete(destination);
319         assertTrue("Check No Exist", !destination.exists());
320     }
321
322     public void testForceDeleteAFile2() throws Exception JavaDoc {
323         File JavaDoc destination = new File JavaDoc(getTestDirectory(), "copy2.txt");
324         destination.createNewFile();
325         assertTrue("Copy2.txt doesn't exist to delete", destination.exists());
326         FileUtils.forceDelete(destination);
327         assertTrue("Check No Exist", !destination.exists());
328     }
329
330     // copyFileToDirectory
331

332     public void testCopyFile1ToDir() throws Exception JavaDoc {
333         File JavaDoc directory = new File JavaDoc(getTestDirectory(), "subdir");
334         if (!directory.exists())
335             directory.mkdirs();
336         File JavaDoc destination = new File JavaDoc(directory, testFile1.getName());
337         
338         //Thread.sleep(LAST_MODIFIED_DELAY);
339
//This is to slow things down so we can catch if
340
//the lastModified date is not ok
341

342         FileUtils.copyFileToDirectory(testFile1, directory);
343         assertTrue("Check Exist", destination.exists());
344         assertTrue("Check Full copy", destination.length() == testFile1Size);
345         /* disabled: Thread.sleep doesn't work reliantly for this case
346         assertTrue("Check last modified date preserved",
347             testFile1.lastModified() == destination.lastModified());*/

348             
349         try {
350             FileUtils.copyFileToDirectory(destination, directory);
351             fail("Should not be able to copy a file into the same directory as itself");
352         } catch (IOException JavaDoc ioe) {
353             //we want that, cannot copy to the same directory as the original file
354
}
355     }
356
357     public void testCopyFile2ToDir() throws Exception JavaDoc {
358         File JavaDoc directory = new File JavaDoc(getTestDirectory(), "subdir");
359         if (!directory.exists())
360             directory.mkdirs();
361         File JavaDoc destination = new File JavaDoc(directory, testFile1.getName());
362         
363         //Thread.sleep(LAST_MODIFIED_DELAY);
364
//This is to slow things down so we can catch if
365
//the lastModified date is not ok
366

367         FileUtils.copyFileToDirectory(testFile1, directory);
368         assertTrue("Check Exist", destination.exists());
369         assertTrue("Check Full copy", destination.length() == testFile2Size);
370         /* disabled: Thread.sleep doesn't work reliantly for this case
371         assertTrue("Check last modified date preserved",
372             testFile1.lastModified() == destination.lastModified());*/

373     }
374
375     // forceDelete
376

377     public void testForceDeleteDir() throws Exception JavaDoc {
378         FileUtils.forceDelete(getTestDirectory().getParentFile());
379         assertTrue(
380             "Check No Exist",
381             !getTestDirectory().getParentFile().exists());
382     }
383
384     private String JavaDoc replaceAll(
385         String JavaDoc text,
386         String JavaDoc lookFor,
387         String JavaDoc replaceWith) {
388         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(text);
389         while (true) {
390             int idx = sb.toString().indexOf(lookFor);
391             if (idx < 0) {
392                 break;
393             }
394             sb.replace(idx, idx + lookFor.length(), replaceWith);
395         }
396         return sb.toString();
397     }
398
399     /**
400      * Test the FileUtils implementation.
401      */

402     // Used to exist as IOTestCase class
403
public void testFileUtils() throws Exception JavaDoc {
404         // Loads file from classpath
405
File JavaDoc file1 = new File JavaDoc(getTestDirectory(), "test.txt");
406         String JavaDoc filename = file1.getAbsolutePath();
407         
408         //Create test file on-the-fly (used to be in CVS)
409
OutputStream JavaDoc out = new java.io.FileOutputStream JavaDoc(file1);
410         try {
411             out.write("This is a test".getBytes("UTF-8"));
412         } finally {
413             out.close();
414         }
415         
416         File JavaDoc file2 = new File JavaDoc(getTestDirectory(), "test2.txt");
417         String JavaDoc filename2 = file2.getAbsolutePath();
418
419 //1.0 These lines commented out as FilenameUtils not in 1.0
420
//1.0 assertTrue(
421
//1.0 "test.txt extension == \"txt\"",
422
//1.0 FilenameUtils.getExtension(filename).equals("txt"));
423

424 //1.0 assertTrue(
425
//1.0 "Test file does not exist: " + filename,
426
//1.0 FilenameUtils.fileExists(filename));
427

428 //1.0 assertTrue(
429
//1.0 "Second test file does not exist",
430
//1.0 !FilenameUtils.fileExists(filename2));
431

432         FileUtils.writeStringToFile(file2, filename, "UTF-8");
433         assertTrue(file2.exists());
434         assertTrue(file2.length() > 0);
435
436         String JavaDoc file2contents = FileUtils.readFileToString(file2, "UTF-8");
437         assertTrue(
438             "Second file's contents correct",
439             filename.equals(file2contents));
440
441         assertTrue(file2.delete());
442         
443 //1.0 FilenameUtils.fileDelete(filename2);
444
//1.0 assertTrue(
445
//1.0 "Second test file does not exist",
446
//1.0 !FilenameUtils.fileExists(filename2));
447

448         String JavaDoc contents = FileUtils.readFileToString(new File JavaDoc(filename), "UTF-8");
449         assertTrue("FileUtils.fileRead()", contents.equals("This is a test"));
450
451     }
452
453 }
454
Popular Tags