1 2 package example.filestorage; 3 4 import junit.framework.TestCase; 5 import java.io.*; 6 import java.util.Arrays; 7 8 /*** 9 * 10 * JUnit test case 11 * 12 * @author Sean C. Sullivan 13 * 14 * 15 */ 16 public class FileStorageTestCase extends TestCase 17 { 18 public void setUp() throws Exception 19 { 20 DerbyDBSetup.dropAll(); 21 DerbyDBSetup.create(); 22 } 23 24 25 public void test() throws Exception 26 { 27 FileStorageDAO dao = DAOFactory.getFileStorageDAO(); 28 29 byte[] sourceData = "hello".getBytes(); 30 InputStream input = new ByteArrayInputStream(sourceData); 31 String filename = "foobar.txt"; 32 long id = dao.saveFile(filename, input, sourceData.length); 33 34 FileInfo info = dao.getFileInfo(id); 35 36 assertEquals( id, info.getId() ); 37 assertEquals( filename, info.getFilename()); 38 assertEquals( sourceData.length, info.getFileSize()); 39 40 assertTrue( dao.fileExists(info.getFilename()) ); 41 42 assertNotNull(info); 43 44 byte[] filedata = dao.getFileData(id); 45 46 assertEquals( sourceData.length, filedata.length); 47 48 assertTrue( Arrays.equals(sourceData, filedata) ); 49 50 java.util.List files = dao.getAllFiles(); 51 52 assertTrue( files.size() > 0 ); 53 54 dao.deleteFile(id); 55 56 info = dao.getFileInfo(id); 57 58 assertNull(info); 59 60 input = new ByteArrayInputStream(sourceData); 61 id = dao.saveFile(filename, input, sourceData.length); 62 63 byte[] overwrite = "overwrite".getBytes(); 64 ByteArrayInputStream inputOverwrite = new ByteArrayInputStream(overwrite); 65 66 dao.overwriteFile(id, inputOverwrite, overwrite.length); 67 68 info = dao.getFileInfo(id); 69 70 assertEquals(overwrite.length, info.getFileSize()); 71 72 assertTrue( Arrays.equals(overwrite, dao.getFileData(id)) ); 73 74 ByteArrayOutputStream out = new ByteArrayOutputStream(); 75 dao.getFileData(id, out); 76 77 assertTrue( Arrays.equals(overwrite, out.toByteArray())); 78 79 dao.deleteFile(id); 80 81 byte[] large = getLargeFileData(); 82 id = dao.saveFile("largefile.bin", 83 new ByteArrayInputStream(large), 84 large.length); 85 boolean deleted = dao.deleteFile(id); 86 assertTrue(deleted); 87 } 88 89 private static byte[] getLargeFileData() 90 { 91 byte[] data = new byte[6000000]; 92 Arrays.fill(data, (byte) 'A'); 93 return data; 94 } 95 96 }