You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TestUtil.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. /*
  2. Copyright (c) 2015 James Ahlborn
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package com.healthmarketscience.jackcess;
  14. import java.io.DataInputStream;
  15. import java.io.File;
  16. import java.io.FileInputStream;
  17. import java.io.FileOutputStream;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.io.OutputStream;
  21. import java.io.PrintWriter;
  22. import java.lang.reflect.Field;
  23. import java.nio.ByteBuffer;
  24. import java.nio.channels.FileChannel;
  25. import java.nio.charset.Charset;
  26. import java.time.Instant;
  27. import java.time.LocalDateTime;
  28. import java.time.ZoneId;
  29. import java.util.ArrayList;
  30. import java.util.Arrays;
  31. import java.util.Calendar;
  32. import java.util.Date;
  33. import java.util.List;
  34. import java.util.Map;
  35. import java.util.TimeZone;
  36. import static com.healthmarketscience.jackcess.Database.*;
  37. import com.healthmarketscience.jackcess.complex.ComplexValueForeignKey;
  38. import com.healthmarketscience.jackcess.impl.ByteUtil;
  39. import com.healthmarketscience.jackcess.impl.DatabaseImpl;
  40. import com.healthmarketscience.jackcess.impl.IndexData;
  41. import com.healthmarketscience.jackcess.impl.IndexImpl;
  42. import com.healthmarketscience.jackcess.impl.JetFormatTest;
  43. import com.healthmarketscience.jackcess.impl.JetFormatTest.TestDB;
  44. import com.healthmarketscience.jackcess.impl.RowIdImpl;
  45. import com.healthmarketscience.jackcess.impl.RowImpl;
  46. import com.healthmarketscience.jackcess.util.MemFileChannel;
  47. import org.junit.Assert;
  48. /**
  49. * Utilty code for the test cases.
  50. *
  51. * @author James Ahlborn
  52. */
  53. @SuppressWarnings("deprecation")
  54. public class TestUtil
  55. {
  56. public static final TimeZone TEST_TZ =
  57. TimeZone.getTimeZone("America/New_York");
  58. private static final ThreadLocal<Boolean> _autoSync =
  59. new ThreadLocal<Boolean>();
  60. private TestUtil() {}
  61. static void setTestAutoSync(boolean autoSync) {
  62. _autoSync.set(autoSync);
  63. }
  64. static void clearTestAutoSync() {
  65. _autoSync.remove();
  66. }
  67. static boolean getTestAutoSync() {
  68. Boolean autoSync = _autoSync.get();
  69. return ((autoSync != null) ? autoSync : Database.DEFAULT_AUTO_SYNC);
  70. }
  71. public static Database open(FileFormat fileFormat, File file)
  72. throws Exception
  73. {
  74. return open(fileFormat, file, false);
  75. }
  76. public static Database open(FileFormat fileFormat, File file, boolean inMem)
  77. throws Exception
  78. {
  79. return open(fileFormat, file, inMem, null);
  80. }
  81. public static Database open(FileFormat fileFormat, File file, boolean inMem,
  82. Charset charset)
  83. throws Exception
  84. {
  85. return openDB(fileFormat, file, inMem, charset, true);
  86. }
  87. public static Database open(TestDB testDB) throws Exception {
  88. return open(testDB.getExpectedFileFormat(), testDB.getFile(), false,
  89. testDB.getExpectedCharset());
  90. }
  91. public static Database openMem(TestDB testDB) throws Exception {
  92. return openDB(testDB.getExpectedFileFormat(), testDB.getFile(), true,
  93. testDB.getExpectedCharset(), false);
  94. }
  95. public static Database create(FileFormat fileFormat) throws Exception {
  96. return create(fileFormat, false);
  97. }
  98. public static Database create(FileFormat fileFormat, boolean keep)
  99. throws Exception
  100. {
  101. return create(fileFormat, keep, true);
  102. }
  103. public static Database createMem(FileFormat fileFormat) throws Exception {
  104. return create(fileFormat);
  105. }
  106. public static Database createFile(FileFormat fileFormat) throws Exception {
  107. return create(fileFormat, false, false);
  108. }
  109. private static Database create(FileFormat fileFormat, boolean keep,
  110. boolean inMem)
  111. throws Exception
  112. {
  113. FileChannel channel = ((inMem && !keep) ? MemFileChannel.newChannel() :
  114. null);
  115. if (fileFormat == FileFormat.GENERIC_JET4) {
  116. // while we don't support creating GENERIC_JET4 as a jackcess feature,
  117. // we do want to be able to test these types of dbs
  118. InputStream inStream = null;
  119. OutputStream outStream = null;
  120. try {
  121. inStream = TestUtil.class.getClassLoader()
  122. .getResourceAsStream("emptyJet4.mdb");
  123. File f = createTempFile(keep);
  124. if (channel != null) {
  125. JetFormatTest.transferDbFrom(channel, inStream);
  126. } else {
  127. ByteUtil.copy(inStream, outStream = new FileOutputStream(f));
  128. outStream.close();
  129. }
  130. return new DatabaseBuilder(f)
  131. .setAutoSync(getTestAutoSync()).setChannel(channel).open();
  132. } finally {
  133. ByteUtil.closeQuietly(inStream);
  134. ByteUtil.closeQuietly(outStream);
  135. }
  136. }
  137. return new DatabaseBuilder(createTempFile(keep)).setFileFormat(fileFormat)
  138. .setAutoSync(getTestAutoSync()).setChannel(channel).create();
  139. }
  140. public static Database openCopy(TestDB testDB) throws Exception {
  141. return openCopy(testDB, false);
  142. }
  143. public static Database openCopy(TestDB testDB, boolean keep)
  144. throws Exception
  145. {
  146. return openCopy(testDB.getExpectedFileFormat(), testDB.getFile(), keep);
  147. }
  148. public static Database openCopy(FileFormat fileFormat, File file)
  149. throws Exception
  150. {
  151. return openCopy(fileFormat, file, false);
  152. }
  153. public static Database openCopy(FileFormat fileFormat, File file,
  154. boolean keep)
  155. throws Exception
  156. {
  157. File tmp = createTempFile(keep);
  158. copyFile(file, tmp);
  159. return openDB(fileFormat, tmp, false, null, false);
  160. }
  161. private static Database openDB(
  162. FileFormat fileFormat, File file, boolean inMem, Charset charset,
  163. boolean readOnly)
  164. throws Exception
  165. {
  166. FileChannel channel = (inMem ? MemFileChannel.newChannel(
  167. file, MemFileChannel.RW_CHANNEL_MODE)
  168. : null);
  169. final Database db = new DatabaseBuilder(file).setReadOnly(readOnly)
  170. .setAutoSync(getTestAutoSync()).setChannel(channel)
  171. .setCharset(charset).open();
  172. Assert.assertEquals("Wrong JetFormat.",
  173. DatabaseImpl.getFileFormatDetails(fileFormat).getFormat(),
  174. ((DatabaseImpl)db).getFormat());
  175. Assert.assertEquals("Wrong FileFormat.", fileFormat, db.getFileFormat());
  176. return db;
  177. }
  178. static Object[] createTestRow(String col1Val) {
  179. return new Object[] {col1Val, "R", "McCune", 1234, (byte) 0xad, 555.66d,
  180. 777.88f, (short) 999, new Date()};
  181. }
  182. public static Object[] createTestRow() {
  183. return createTestRow("Tim");
  184. }
  185. static Map<String,Object> createTestRowMap(String col1Val) {
  186. return createExpectedRow("A", col1Val, "B", "R", "C", "McCune",
  187. "D", 1234, "E", (byte) 0xad, "F", 555.66d,
  188. "G", 777.88f, "H", (short) 999, "I", new Date());
  189. }
  190. public static void createTestTable(Database db) throws Exception {
  191. new TableBuilder("test")
  192. .addColumn(new ColumnBuilder("A", DataType.TEXT))
  193. .addColumn(new ColumnBuilder("B", DataType.TEXT))
  194. .addColumn(new ColumnBuilder("C", DataType.TEXT))
  195. .addColumn(new ColumnBuilder("D", DataType.LONG))
  196. .addColumn(new ColumnBuilder("E", DataType.BYTE))
  197. .addColumn(new ColumnBuilder("F", DataType.DOUBLE))
  198. .addColumn(new ColumnBuilder("G", DataType.FLOAT))
  199. .addColumn(new ColumnBuilder("H", DataType.INT))
  200. .addColumn(new ColumnBuilder("I", DataType.SHORT_DATE_TIME))
  201. .toTable(db);
  202. }
  203. public static String createString(int len) {
  204. return createString(len, 'a');
  205. }
  206. static String createNonAsciiString(int len) {
  207. return createString(len, '\u0CC0');
  208. }
  209. private static String createString(int len, char firstChar) {
  210. StringBuilder builder = new StringBuilder(len);
  211. for(int i = 0; i < len; ++i) {
  212. builder.append((char)(firstChar + (i % 26)));
  213. }
  214. return builder.toString();
  215. }
  216. static void assertRowCount(int expectedRowCount, Table table)
  217. throws Exception
  218. {
  219. Assert.assertEquals(expectedRowCount, countRows(table));
  220. Assert.assertEquals(expectedRowCount, table.getRowCount());
  221. }
  222. public static int countRows(Table table) throws Exception {
  223. int rtn = 0;
  224. for(Map<String, Object> row : CursorBuilder.createCursor(table)) {
  225. rtn++;
  226. }
  227. return rtn;
  228. }
  229. public static void assertTable(
  230. List<? extends Map<String, Object>> expectedTable,
  231. Table table)
  232. throws IOException
  233. {
  234. assertCursor(expectedTable, CursorBuilder.createCursor(table));
  235. }
  236. public static void assertCursor(
  237. List<? extends Map<String, Object>> expectedTable,
  238. Cursor cursor)
  239. {
  240. List<Map<String, Object>> foundTable =
  241. new ArrayList<Map<String, Object>>();
  242. for(Map<String, Object> row : cursor) {
  243. foundTable.add(row);
  244. }
  245. Assert.assertEquals(expectedTable.size(), foundTable.size());
  246. for(int i = 0; i < expectedTable.size(); ++i) {
  247. Assert.assertEquals(expectedTable.get(i), foundTable.get(i));
  248. }
  249. }
  250. public static RowImpl createExpectedRow(Object... rowElements) {
  251. RowImpl row = new RowImpl((RowIdImpl)null);
  252. for(int i = 0; i < rowElements.length; i += 2) {
  253. row.put((String)rowElements[i],
  254. rowElements[i + 1]);
  255. }
  256. return row;
  257. }
  258. public static List<Row> createExpectedTable(Row... rows) {
  259. return Arrays.<Row>asList(rows);
  260. }
  261. public static void dumpDatabase(Database mdb) throws Exception {
  262. dumpDatabase(mdb, false);
  263. }
  264. public static void dumpDatabase(Database mdb, boolean systemTables)
  265. throws Exception
  266. {
  267. dumpDatabase(mdb, systemTables, new PrintWriter(System.out, true));
  268. }
  269. public static void dumpTable(Table table) throws Exception {
  270. dumpTable(table, new PrintWriter(System.out, true));
  271. }
  272. static void dumpDatabase(Database mdb, boolean systemTables,
  273. PrintWriter writer) throws Exception
  274. {
  275. writer.println("DATABASE:");
  276. for(Table table : mdb) {
  277. dumpTable(table, writer);
  278. }
  279. if(systemTables) {
  280. for(String sysTableName : mdb.getSystemTableNames()) {
  281. dumpTable(mdb.getSystemTable(sysTableName), writer);
  282. }
  283. }
  284. }
  285. static void dumpTable(Table table, PrintWriter writer) throws Exception {
  286. // make sure all indexes are read
  287. for(Index index : table.getIndexes()) {
  288. ((IndexImpl)index).initialize();
  289. }
  290. writer.println("TABLE: " + table.getName());
  291. List<String> colNames = new ArrayList<String>();
  292. for(Column col : table.getColumns()) {
  293. colNames.add(col.getName());
  294. }
  295. writer.println("COLUMNS: " + colNames);
  296. for(Map<String, Object> row : CursorBuilder.createCursor(table)) {
  297. writer.println(massageRow(row));
  298. }
  299. }
  300. private static Map<String,Object> massageRow(Map<String, Object> row)
  301. throws IOException
  302. {
  303. for(Map.Entry<String, Object> entry : row.entrySet()) {
  304. Object v = entry.getValue();
  305. if(v instanceof byte[]) {
  306. // make byte[] printable
  307. byte[] bv = (byte[])v;
  308. entry.setValue(ByteUtil.toHexString(ByteBuffer.wrap(bv), bv.length));
  309. } else if(v instanceof ComplexValueForeignKey) {
  310. // deref complex values
  311. String str = "ComplexValue(" + v + ")" +
  312. ((ComplexValueForeignKey)v).getValues();
  313. entry.setValue(str);
  314. }
  315. }
  316. return row;
  317. }
  318. static void dumpIndex(Index index) throws Exception {
  319. dumpIndex(index, new PrintWriter(System.out, true));
  320. }
  321. static void dumpIndex(Index index, PrintWriter writer) throws Exception {
  322. writer.println("INDEX: " + index);
  323. IndexData.EntryCursor ec = ((IndexImpl)index).cursor();
  324. IndexData.Entry lastE = ec.getLastEntry();
  325. IndexData.Entry e = null;
  326. while((e = ec.getNextEntry()) != lastE) {
  327. writer.println(e);
  328. }
  329. }
  330. static void assertSameDate(Date expected, Date found)
  331. {
  332. if(expected == found) {
  333. return;
  334. }
  335. if((expected == null) || (found == null)) {
  336. throw new AssertionError("Expected " + expected + ", found " + found);
  337. }
  338. long expTime = expected.getTime();
  339. long foundTime = found.getTime();
  340. // there are some rounding issues due to dates being stored as doubles,
  341. // but it results in a 1 millisecond difference, so i'm not going to worry
  342. // about it
  343. if((expTime != foundTime) && (Math.abs(expTime - foundTime) > 1)) {
  344. throw new AssertionError("Expected " + expTime + " (" + expected +
  345. "), found " + foundTime + " (" + found + ")");
  346. }
  347. }
  348. static void assertSameDate(Date expected, LocalDateTime found)
  349. {
  350. if((expected == null) && (found == null)) {
  351. return;
  352. }
  353. if((expected == null) || (found == null)) {
  354. throw new AssertionError("Expected " + expected + ", found " + found);
  355. }
  356. LocalDateTime expectedLdt = LocalDateTime.ofInstant(
  357. Instant.ofEpochMilli(expected.getTime()),
  358. ZoneId.systemDefault());
  359. Assert.assertEquals(expectedLdt, found);
  360. }
  361. public static void copyFile(File srcFile, File dstFile)
  362. throws IOException
  363. {
  364. // FIXME should really be using commons io FileUtils here, but don't want
  365. // to add dep for one simple test method
  366. OutputStream ostream = new FileOutputStream(dstFile);
  367. InputStream istream = new FileInputStream(srcFile);
  368. try {
  369. copyStream(istream, ostream);
  370. } finally {
  371. ostream.close();
  372. }
  373. }
  374. static void copyStream(InputStream istream, OutputStream ostream)
  375. throws IOException
  376. {
  377. // FIXME should really be using commons io FileUtils here, but don't want
  378. // to add dep for one simple test method
  379. byte[] buf = new byte[1024];
  380. int numBytes = 0;
  381. while((numBytes = istream.read(buf)) >= 0) {
  382. ostream.write(buf, 0, numBytes);
  383. }
  384. }
  385. public static File createTempFile(boolean keep) throws Exception {
  386. File tmp = File.createTempFile("databaseTest", ".mdb");
  387. if(keep) {
  388. System.out.println("Created " + tmp);
  389. } else {
  390. tmp.deleteOnExit();
  391. }
  392. return tmp;
  393. }
  394. public static void clearTableCache(Database db) throws Exception
  395. {
  396. Field f = db.getClass().getDeclaredField("_tableCache");
  397. f.setAccessible(true);
  398. Object val = f.get(db);
  399. f = val.getClass().getDeclaredField("_tables");
  400. f.setAccessible(true);
  401. val = f.get(val);
  402. ((Map<?,?>)val).clear();
  403. }
  404. public static byte[] toByteArray(File file)
  405. throws IOException
  406. {
  407. return toByteArray(new FileInputStream(file), file.length());
  408. }
  409. public static byte[] toByteArray(InputStream in, long length)
  410. throws IOException
  411. {
  412. // FIXME should really be using commons io IOUtils here, but don't want
  413. // to add dep for one simple test method
  414. try {
  415. DataInputStream din = new DataInputStream(in);
  416. byte[] bytes = new byte[(int)length];
  417. din.readFully(bytes);
  418. return bytes;
  419. } finally {
  420. in.close();
  421. }
  422. }
  423. static void checkTestDBTable1RowABCDEFG(final TestDB testDB, final Table table, final Row row)
  424. throws IOException {
  425. Assert.assertEquals("testDB: " + testDB + "; table: " + table, "abcdefg", row.get("A"));
  426. Assert.assertEquals("hijklmnop", row.get("B"));
  427. Assert.assertEquals(new Byte((byte) 2), row.get("C"));
  428. Assert.assertEquals(new Short((short) 222), row.get("D"));
  429. Assert.assertEquals(new Integer(333333333), row.get("E"));
  430. Assert.assertEquals(new Double(444.555d), row.get("F"));
  431. final Calendar cal = Calendar.getInstance();
  432. cal.setTime(row.getDate("G"));
  433. Assert.assertEquals(Calendar.SEPTEMBER, cal.get(Calendar.MONTH));
  434. Assert.assertEquals(21, cal.get(Calendar.DAY_OF_MONTH));
  435. Assert.assertEquals(1974, cal.get(Calendar.YEAR));
  436. Assert.assertEquals(0, cal.get(Calendar.HOUR_OF_DAY));
  437. Assert.assertEquals(0, cal.get(Calendar.MINUTE));
  438. Assert.assertEquals(0, cal.get(Calendar.SECOND));
  439. Assert.assertEquals(0, cal.get(Calendar.MILLISECOND));
  440. Assert.assertEquals(Boolean.TRUE, row.get("I"));
  441. }
  442. static void checkTestDBTable1RowA(final TestDB testDB, final Table table, final Row row)
  443. throws IOException {
  444. Assert.assertEquals("testDB: " + testDB + "; table: " + table, "a", row.get("A"));
  445. Assert.assertEquals("b", row.get("B"));
  446. Assert.assertEquals(new Byte((byte) 0), row.get("C"));
  447. Assert.assertEquals(new Short((short) 0), row.get("D"));
  448. Assert.assertEquals(new Integer(0), row.get("E"));
  449. Assert.assertEquals(new Double(0d), row.get("F"));
  450. final Calendar cal = Calendar.getInstance();
  451. cal.setTime(row.getDate("G"));
  452. Assert.assertEquals(Calendar.DECEMBER, cal.get(Calendar.MONTH));
  453. Assert.assertEquals(12, cal.get(Calendar.DAY_OF_MONTH));
  454. Assert.assertEquals(1981, cal.get(Calendar.YEAR));
  455. Assert.assertEquals(0, cal.get(Calendar.HOUR_OF_DAY));
  456. Assert.assertEquals(0, cal.get(Calendar.MINUTE));
  457. Assert.assertEquals(0, cal.get(Calendar.SECOND));
  458. Assert.assertEquals(0, cal.get(Calendar.MILLISECOND));
  459. Assert.assertEquals(Boolean.FALSE, row.get("I"));
  460. }
  461. }