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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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 static org.junit.jupiter.api.Assertions.*;
  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. if(fileFormat != null) {
  173. assertEquals(DatabaseImpl.getFileFormatDetails(fileFormat).getFormat(),
  174. ((DatabaseImpl)db).getFormat(),
  175. "Wrong JetFormat.");
  176. assertEquals(fileFormat, db.getFileFormat(), "Wrong FileFormat.");
  177. }
  178. return db;
  179. }
  180. static Object[] createTestRow(String col1Val) {
  181. return new Object[] {col1Val, "R", "McCune", 1234, (byte) 0xad, 555.66d,
  182. 777.88f, (short) 999, new Date()};
  183. }
  184. public static Object[] createTestRow() {
  185. return createTestRow("Tim");
  186. }
  187. static Map<String,Object> createTestRowMap(String col1Val) {
  188. return createExpectedRow("A", col1Val, "B", "R", "C", "McCune",
  189. "D", 1234, "E", (byte) 0xad, "F", 555.66d,
  190. "G", 777.88f, "H", (short) 999, "I", new Date());
  191. }
  192. public static void createTestTable(Database db) throws Exception {
  193. new TableBuilder("test")
  194. .addColumn(new ColumnBuilder("A", DataType.TEXT))
  195. .addColumn(new ColumnBuilder("B", DataType.TEXT))
  196. .addColumn(new ColumnBuilder("C", DataType.TEXT))
  197. .addColumn(new ColumnBuilder("D", DataType.LONG))
  198. .addColumn(new ColumnBuilder("E", DataType.BYTE))
  199. .addColumn(new ColumnBuilder("F", DataType.DOUBLE))
  200. .addColumn(new ColumnBuilder("G", DataType.FLOAT))
  201. .addColumn(new ColumnBuilder("H", DataType.INT))
  202. .addColumn(new ColumnBuilder("I", DataType.SHORT_DATE_TIME))
  203. .toTable(db);
  204. }
  205. public static String createString(int len) {
  206. return createString(len, 'a');
  207. }
  208. static String createNonAsciiString(int len) {
  209. return createString(len, '\u0CC0');
  210. }
  211. private static String createString(int len, char firstChar) {
  212. StringBuilder builder = new StringBuilder(len);
  213. for(int i = 0; i < len; ++i) {
  214. builder.append((char)(firstChar + (i % 26)));
  215. }
  216. return builder.toString();
  217. }
  218. static void assertRowCount(int expectedRowCount, Table table)
  219. throws Exception
  220. {
  221. assertEquals(expectedRowCount, countRows(table));
  222. assertEquals(expectedRowCount, table.getRowCount());
  223. }
  224. public static int countRows(Table table) throws Exception {
  225. int rtn = 0;
  226. for(Map<String, Object> row : CursorBuilder.createCursor(table)) {
  227. rtn++;
  228. }
  229. return rtn;
  230. }
  231. public static void assertTable(
  232. List<? extends Map<String, Object>> expectedTable,
  233. Table table)
  234. throws IOException
  235. {
  236. assertCursor(expectedTable, CursorBuilder.createCursor(table));
  237. }
  238. public static void assertCursor(
  239. List<? extends Map<String, Object>> expectedTable,
  240. Cursor cursor)
  241. {
  242. List<Map<String, Object>> foundTable =
  243. new ArrayList<Map<String, Object>>();
  244. for(Map<String, Object> row : cursor) {
  245. foundTable.add(row);
  246. }
  247. assertEquals(expectedTable.size(), foundTable.size());
  248. for(int i = 0; i < expectedTable.size(); ++i) {
  249. assertEquals(expectedTable.get(i), foundTable.get(i));
  250. }
  251. }
  252. public static RowImpl createExpectedRow(Object... rowElements) {
  253. RowImpl row = new RowImpl((RowIdImpl)null);
  254. for(int i = 0; i < rowElements.length; i += 2) {
  255. row.put((String)rowElements[i],
  256. rowElements[i + 1]);
  257. }
  258. return row;
  259. }
  260. public static List<Row> createExpectedTable(Row... rows) {
  261. return Arrays.<Row>asList(rows);
  262. }
  263. public static void dumpDatabase(Database mdb) throws Exception {
  264. dumpDatabase(mdb, false);
  265. }
  266. public static void dumpDatabase(Database mdb, boolean systemTables)
  267. throws Exception
  268. {
  269. dumpDatabase(mdb, systemTables, new PrintWriter(System.out, true));
  270. }
  271. public static void dumpTable(Table table) throws Exception {
  272. dumpTable(table, new PrintWriter(System.out, true));
  273. }
  274. public static void dumpProperties(Table table) throws Exception {
  275. System.out.println("TABLE_PROPS: " + table.getName() + ": " +
  276. table.getProperties());
  277. for(Column c : table.getColumns()) {
  278. System.out.println("COL_PROPS: " + c.getName() + ": " +
  279. c.getProperties());
  280. }
  281. }
  282. static void dumpDatabase(Database mdb, boolean systemTables,
  283. PrintWriter writer) throws Exception
  284. {
  285. writer.println("DATABASE:");
  286. for(Table table : mdb) {
  287. dumpTable(table, writer);
  288. }
  289. if(systemTables) {
  290. for(String sysTableName : mdb.getSystemTableNames()) {
  291. dumpTable(mdb.getSystemTable(sysTableName), writer);
  292. }
  293. }
  294. }
  295. static void dumpTable(Table table, PrintWriter writer) throws Exception {
  296. // make sure all indexes are read
  297. for(Index index : table.getIndexes()) {
  298. ((IndexImpl)index).initialize();
  299. }
  300. writer.println("TABLE: " + table.getName());
  301. List<String> colNames = new ArrayList<String>();
  302. for(Column col : table.getColumns()) {
  303. colNames.add(col.getName());
  304. }
  305. writer.println("COLUMNS: " + colNames);
  306. for(Map<String, Object> row : CursorBuilder.createCursor(table)) {
  307. writer.println(massageRow(row));
  308. }
  309. }
  310. private static Map<String,Object> massageRow(Map<String, Object> row)
  311. throws IOException
  312. {
  313. for(Map.Entry<String, Object> entry : row.entrySet()) {
  314. Object v = entry.getValue();
  315. if(v instanceof byte[]) {
  316. // make byte[] printable
  317. byte[] bv = (byte[])v;
  318. entry.setValue(ByteUtil.toHexString(ByteBuffer.wrap(bv), bv.length));
  319. } else if(v instanceof ComplexValueForeignKey) {
  320. // deref complex values
  321. String str = "ComplexValue(" + v + ")" +
  322. ((ComplexValueForeignKey)v).getValues();
  323. entry.setValue(str);
  324. }
  325. }
  326. return row;
  327. }
  328. static void dumpIndex(Index index) throws Exception {
  329. dumpIndex(index, new PrintWriter(System.out, true));
  330. }
  331. static void dumpIndex(Index index, PrintWriter writer) throws Exception {
  332. writer.println("INDEX: " + index);
  333. IndexData.EntryCursor ec = ((IndexImpl)index).cursor();
  334. IndexData.Entry lastE = ec.getLastEntry();
  335. IndexData.Entry e = null;
  336. while((e = ec.getNextEntry()) != lastE) {
  337. writer.println(e);
  338. }
  339. }
  340. static void assertSameDate(Date expected, Date found)
  341. {
  342. if(expected == found) {
  343. return;
  344. }
  345. if((expected == null) || (found == null)) {
  346. throw new AssertionError("Expected " + expected + ", found " + found);
  347. }
  348. long expTime = expected.getTime();
  349. long foundTime = found.getTime();
  350. // there are some rounding issues due to dates being stored as doubles,
  351. // but it results in a 1 millisecond difference, so i'm not going to worry
  352. // about it
  353. if((expTime != foundTime) && (Math.abs(expTime - foundTime) > 1)) {
  354. throw new AssertionError("Expected " + expTime + " (" + expected +
  355. "), found " + foundTime + " (" + found + ")");
  356. }
  357. }
  358. static void assertSameDate(Date expected, LocalDateTime found)
  359. {
  360. if((expected == null) && (found == null)) {
  361. return;
  362. }
  363. if((expected == null) || (found == null)) {
  364. throw new AssertionError("Expected " + expected + ", found " + found);
  365. }
  366. LocalDateTime expectedLdt = LocalDateTime.ofInstant(
  367. Instant.ofEpochMilli(expected.getTime()),
  368. ZoneId.systemDefault());
  369. assertEquals(expectedLdt, found);
  370. }
  371. public static void copyFile(File srcFile, File dstFile)
  372. throws IOException
  373. {
  374. // FIXME should really be using commons io FileUtils here, but don't want
  375. // to add dep for one simple test method
  376. OutputStream ostream = new FileOutputStream(dstFile);
  377. InputStream istream = new FileInputStream(srcFile);
  378. try {
  379. copyStream(istream, ostream);
  380. } finally {
  381. ostream.close();
  382. }
  383. }
  384. static void copyStream(InputStream istream, OutputStream ostream)
  385. throws IOException
  386. {
  387. // FIXME should really be using commons io FileUtils here, but don't want
  388. // to add dep for one simple test method
  389. byte[] buf = new byte[1024];
  390. int numBytes = 0;
  391. while((numBytes = istream.read(buf)) >= 0) {
  392. ostream.write(buf, 0, numBytes);
  393. }
  394. }
  395. public static File createTempFile(boolean keep) throws Exception {
  396. File tmp = File.createTempFile("databaseTest", ".mdb");
  397. if(keep) {
  398. System.out.println("Created " + tmp);
  399. } else {
  400. tmp.deleteOnExit();
  401. }
  402. return tmp;
  403. }
  404. public static void clearTableCache(Database db) throws Exception
  405. {
  406. Field f = db.getClass().getDeclaredField("_tableCache");
  407. f.setAccessible(true);
  408. Object val = f.get(db);
  409. f = val.getClass().getDeclaredField("_tables");
  410. f.setAccessible(true);
  411. val = f.get(val);
  412. ((Map<?,?>)val).clear();
  413. }
  414. public static byte[] toByteArray(File file)
  415. throws IOException
  416. {
  417. return toByteArray(new FileInputStream(file), file.length());
  418. }
  419. public static byte[] toByteArray(InputStream in, long length)
  420. throws IOException
  421. {
  422. // FIXME should really be using commons io IOUtils here, but don't want
  423. // to add dep for one simple test method
  424. try {
  425. DataInputStream din = new DataInputStream(in);
  426. byte[] bytes = new byte[(int)length];
  427. din.readFully(bytes);
  428. return bytes;
  429. } finally {
  430. in.close();
  431. }
  432. }
  433. static void checkTestDBTable1RowABCDEFG(final TestDB testDB, final Table table, final Row row)
  434. throws IOException {
  435. assertEquals("abcdefg", row.get("A"), "testDB: " + testDB + "; table: " + table);
  436. assertEquals("hijklmnop", row.get("B"));
  437. assertEquals(new Byte((byte) 2), row.get("C"));
  438. assertEquals(new Short((short) 222), row.get("D"));
  439. assertEquals(new Integer(333333333), row.get("E"));
  440. assertEquals(new Double(444.555d), row.get("F"));
  441. final Calendar cal = Calendar.getInstance();
  442. cal.setTime(row.getDate("G"));
  443. assertEquals(Calendar.SEPTEMBER, cal.get(Calendar.MONTH));
  444. assertEquals(21, cal.get(Calendar.DAY_OF_MONTH));
  445. assertEquals(1974, cal.get(Calendar.YEAR));
  446. assertEquals(0, cal.get(Calendar.HOUR_OF_DAY));
  447. assertEquals(0, cal.get(Calendar.MINUTE));
  448. assertEquals(0, cal.get(Calendar.SECOND));
  449. assertEquals(0, cal.get(Calendar.MILLISECOND));
  450. assertEquals(Boolean.TRUE, row.get("I"));
  451. }
  452. static void checkTestDBTable1RowA(final TestDB testDB, final Table table, final Row row)
  453. throws IOException {
  454. assertEquals("a", row.get("A"), "testDB: " + testDB + "; table: " + table);
  455. assertEquals("b", row.get("B"));
  456. assertEquals(new Byte((byte) 0), row.get("C"));
  457. assertEquals(new Short((short) 0), row.get("D"));
  458. assertEquals(new Integer(0), row.get("E"));
  459. assertEquals(new Double(0d), row.get("F"));
  460. final Calendar cal = Calendar.getInstance();
  461. cal.setTime(row.getDate("G"));
  462. assertEquals(Calendar.DECEMBER, cal.get(Calendar.MONTH));
  463. assertEquals(12, cal.get(Calendar.DAY_OF_MONTH));
  464. assertEquals(1981, cal.get(Calendar.YEAR));
  465. assertEquals(0, cal.get(Calendar.HOUR_OF_DAY));
  466. assertEquals(0, cal.get(Calendar.MINUTE));
  467. assertEquals(0, cal.get(Calendar.SECOND));
  468. assertEquals(0, cal.get(Calendar.MILLISECOND));
  469. assertEquals(Boolean.FALSE, row.get("I"));
  470. }
  471. }