1/*- 2 * See the file LICENSE for redistribution information. 3 * 4 * Copyright (c) 2002,2008 Oracle. All rights reserved. 5 * 6 * $Id: DbTestUtil.java,v 12.7 2008/01/08 20:58:57 bostic Exp $ 7 */ 8 9package com.sleepycat.collections.test; 10 11import java.io.BufferedInputStream; 12import java.io.BufferedOutputStream; 13import java.io.File; 14import java.io.FileOutputStream; 15import java.io.IOException; 16import java.io.InputStream; 17import java.io.OutputStream; 18 19import junit.framework.TestCase; 20 21import com.sleepycat.db.DatabaseConfig; 22 23/** 24 * @author Mark Hayes 25 */ 26public class DbTestUtil { 27 28 public static final DatabaseConfig DBCONFIG_CREATE = new DatabaseConfig(); 29 static { 30 DBCONFIG_CREATE.setAllowCreate(true); 31 } 32 33 private static final File TEST_DIR; 34 static { 35 String dir = System.getProperty("testdestdir"); 36 if (dir == null || dir.length() == 0) { 37 dir = "."; 38 } 39 TEST_DIR = new File(dir, "tmp"); 40 } 41 42 public static void printTestName(String name) { 43 // don't want verbose printing for now 44 // System.out.println(name); 45 } 46 47 public static File getExistingDir(String name) 48 throws IOException { 49 50 File dir = new File(TEST_DIR, name); 51 if (!dir.exists() || !dir.isDirectory()) { 52 throw new IllegalStateException( 53 "Not an existing directory: " + dir); 54 } 55 return dir; 56 } 57 58 public static File getNewDir() 59 throws IOException { 60 61 return getNewDir("test-dir"); 62 } 63 64 public static File getNewDir(String name) 65 throws IOException { 66 67 File dir = new File(TEST_DIR, name); 68 if (dir.isDirectory()) { 69 String[] files = dir.list(); 70 if (files != null) { 71 for (int i = 0; i < files.length; i += 1) { 72 new File(dir, files[i]).delete(); 73 } 74 } 75 } else { 76 dir.delete(); 77 dir.mkdirs(); 78 } 79 return dir; 80 } 81 82 public static File getNewFile() 83 throws IOException { 84 85 return getNewFile("test-file"); 86 } 87 88 public static File getNewFile(String name) 89 throws IOException { 90 91 return getNewFile(TEST_DIR, name); 92 } 93 94 public static File getNewFile(File dir, String name) 95 throws IOException { 96 97 File file = new File(dir, name); 98 file.delete(); 99 return file; 100 } 101 102 public static boolean copyResource(Class cls, String fileName, File toDir) 103 throws IOException { 104 105 InputStream in = cls.getResourceAsStream("testdata/" + fileName); 106 if (in == null) { 107 return false; 108 } 109 in = new BufferedInputStream(in); 110 File file = new File(toDir, fileName); 111 OutputStream out = new FileOutputStream(file); 112 out = new BufferedOutputStream(out); 113 int c; 114 while ((c = in.read()) >= 0) out.write(c); 115 in.close(); 116 out.close(); 117 return true; 118 } 119 120 public static String qualifiedTestName(TestCase test) { 121 122 String s = test.getClass().getName(); 123 int i = s.lastIndexOf('.'); 124 if (i >= 0) { 125 s = s.substring(i + 1); 126 } 127 return s + '.' + test.getName(); 128 } 129} 130