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

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