This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
/
ZanataDbunitJpaTest.java
445 lines (400 loc) · 14.6 KB
/
ZanataDbunitJpaTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
package org.zanata;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ReplacementDataSet;
import org.dbunit.dataset.datatype.DataType;
import org.dbunit.dataset.datatype.DataTypeException;
import org.dbunit.dataset.datatype.DefaultDataTypeFactory;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.operation.DatabaseOperation;
import org.hibernate.internal.SessionImpl;
import org.junit.After;
import org.junit.Before;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
/**
* Adapted from org.jboss.seam.mock.DBUnitSeamTest
*
* @see org.jboss.seam.mock.DBUnitSeamTest
* @see org.jboss.seam.mock.DBJUnitSeamTest
*/
@Slf4j
public abstract class ZanataDbunitJpaTest extends ZanataJpaTest {
protected String binaryDir;
protected boolean replaceNull = true;
protected List<DataSetOperation> beforeTestOperations =
new ArrayList<DataSetOperation>();
protected List<DataSetOperation> afterTestOperations =
new ArrayList<DataSetOperation>();
private boolean prepared = false;
@BeforeClass
@Parameters("binaryDir")
public void setBinaryDir(@Optional String binaryDir) {
if (binaryDir == null)
return;
this.binaryDir = binaryDir;
}
protected String getBinaryDir() {
return binaryDir;
}
@BeforeClass
@Parameters("replaceNull")
public void setReplaceNull(@Optional Boolean replaceNull) {
if (replaceNull == null)
return;
this.replaceNull = replaceNull;
}
protected Boolean isReplaceNull() {
return replaceNull;
}
@BeforeMethod
@Before
protected void prepareDataBeforeTest() {
// This is not pretty but we unfortunately can not have dependencies
// between @BeforeClass methods.
// This was a basic design mistake and we can't change it now because we
// need to be backwards
// compatible. We can only "prepare" the datasets once all @BeforeClass
// have been executed.
if (!prepared) {
prepareDBUnitOperations();
for (DataSetOperation beforeTestOperation : beforeTestOperations) {
beforeTestOperation.prepare(this);
}
for (DataSetOperation afterTestOperation : afterTestOperations) {
afterTestOperation.prepare(this);
}
prepared = true;
}
executeOperations(beforeTestOperations);
clearCache();
}
@AfterMethod
@After
public void cleanDataAfterTest() {
executeOperations(afterTestOperations);
clearCache();
}
private void clearCache() {
/*
* Session session = getSession();
* session.getSessionFactory().getCache().evictEntityRegions();
* session.getSessionFactory().getCache().evictCollectionRegions();
*/
}
protected void executeOperations(List<DataSetOperation> list) {
IDatabaseConnection con = null;
con = getConnection();
disableReferentialIntegrity(con);
for (DataSetOperation op : list) {
prepareExecution(con, op);
op.execute(con);
afterExecution(con, op);
}
enableReferentialIntegrity(con);
}
protected static class DataSetOperation {
String dataSetLocation;
ReplacementDataSet dataSet;
DatabaseOperation operation;
protected DataSetOperation() {
// Support subclassing
}
/**
* Defaults to <tt>DatabaseOperation.CLEAN_INSERT</tt>
*
* @param dataSetLocation
* location of DBUnit dataset
*/
public DataSetOperation(String dataSetLocation) {
this(dataSetLocation, DatabaseOperation.CLEAN_INSERT);
}
/**
* Defaults to <tt>DatabaseOperation.CLEAN_INSERT</tt>
*
* @param dataSetLocation
* location of DBUnit dataset
* @param dtdLocation
* optional (can be null) location of XML file DTD on
* classpath
*/
public DataSetOperation(String dataSetLocation, String dtdLocation) {
this(dataSetLocation, dtdLocation, DatabaseOperation.CLEAN_INSERT);
}
/**
* @param dataSetLocation
* location of DBUnit dataset
* @param operation
* operation to execute
*/
public DataSetOperation(String dataSetLocation,
DatabaseOperation operation) {
this(dataSetLocation, null, operation);
}
public DataSetOperation(String dataSetLocation, String dtdLocation,
DatabaseOperation operation) {
if (dataSetLocation == null) {
this.operation = operation;
return;
}
// Load the base dataset file
InputStream input =
Thread.currentThread().getContextClassLoader()
.getResourceAsStream(dataSetLocation);
try {
FlatXmlDataSetBuilder dataSetBuilder =
new FlatXmlDataSetBuilder();
dataSetBuilder.setColumnSensing(true);
InputStream dtdInput = null;
if (dtdLocation != null) {
dtdInput =
Thread.currentThread().getContextClassLoader()
.getResourceAsStream(dtdLocation);
}
if (dtdInput == null) {
this.dataSet =
new ReplacementDataSet(dataSetBuilder.build(input));
} else {
dataSetBuilder.setMetaDataSetFromDtd(dtdInput);
this.dataSet =
new ReplacementDataSet(dataSetBuilder.build(input));
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
this.operation = operation;
this.dataSetLocation = dataSetLocation;
}
public IDataSet getDataSet() {
return dataSet;
}
public DatabaseOperation getOperation() {
return operation;
}
public void prepare(ZanataDbunitJpaTest test) {
if (dataSet == null)
return;
if (test.isReplaceNull()) {
dataSet.addReplacementObject("[NULL]", null);
}
if (test.getBinaryDir() != null) {
dataSet.addReplacementSubstring("[BINARY_DIR]", test
.getBinaryDirFullpath().toString());
}
}
public void execute(IDatabaseConnection connection) {
if (dataSet == null || operation == null)
return;
try {
this.operation.execute(connection, dataSet);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@Override
public String toString() {
return getClass().getName() + " with dataset location: "
+ dataSetLocation;
}
}
/**
* Override this method if you want to provide your own DBUnit
* <tt>IDatabaseConnection</tt> instance.
* <p/>
* If you do not override this, default behavior is to use the * configured
* datasource name and to obtain a connection with a JNDI lookup.
*
* @return a DBUnit database connection (wrapped)
*/
// TODO This is hibernate specific
protected IDatabaseConnection getConnection() {
try {
return new DatabaseConnection(
((SessionImpl) getSession()).connection());
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* Execute whatever statement is necessary to either defer or disable
* foreign key constraint checking on the given database connection, which
* is used by DBUnit to import datasets.
*
* @param con
* A DBUnit connection wrapper, which is used afterwards for
* dataset operations
*/
protected void disableReferentialIntegrity(IDatabaseConnection con) {
try {
con.getConnection()
.prepareStatement("set referential_integrity FALSE")
.execute(); // HSQL
// DB
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* Execute whatever statement is necessary to enable integrity constraint
* checks after dataset operations.
*
* @param con
* A DBUnit connection wrapper, before it is used by the
* application again
*/
protected void enableReferentialIntegrity(IDatabaseConnection con) {
try {
con.getConnection()
.prepareStatement("set referential_integrity TRUE")
.execute(); // HSQL
// DB
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* Override this method if you require DBUnit configuration features or
* additional properties.
* <p/>
* Called after a connection has been obtaind and before the connection is
* used. Can be a NOOP method if no additional settings are necessary for
* your DBUnit/DBMS setup.
*
* @param config
* A DBUnit <tt>DatabaseConfig</tt> object for setting properties
* and features
*/
protected void editConfig(DatabaseConfig config) {
// DBUnit/HSQL bugfix
// http://www.carbonfive.com/community/archives/2005/07/dbunit_hsql_and.html
config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY,
new DefaultDataTypeFactory() {
@Override
public DataType createDataType(int sqlType,
String sqlTypeName) throws DataTypeException {
if (sqlType == Types.BOOLEAN) {
return DataType.BOOLEAN;
}
return super.createDataType(sqlType, sqlTypeName);
}
});
}
/**
* Callback for each operation before DBUnit executes the operation, useful
* if extra preparation of data/tables is necessary, e.g. additional SQL
* commands on a per-operation (per table?) granularity on the given
* database connection.
*
* @param con
* A DBUnit connection wrapper
* @param operation
* The operation to be executed, call <tt>getDataSet()</tt> to
* access the data.
*/
protected void prepareExecution(IDatabaseConnection con,
DataSetOperation operation) {
}
/**
* Callback for each operation, useful if extra preparation of data/tables
* is necessary.
*
* @param con
* A DBUnit connection wrapper
* @param operation
* The operation that was executed, call <tt>getDataSet()</tt> to
* access the data.
*/
protected void afterExecution(IDatabaseConnection con,
DataSetOperation operation) {
}
/**
* Resolves the binary dir location with the help of the classloader, we
* need the absolute full path of that directory.
*
* @return URL full absolute path of the binary directory
*/
protected URL getBinaryDirFullpath() {
if (getBinaryDir() == null) {
throw new RuntimeException(
"Please set binaryDir TestNG property to location of binary test files");
}
return getResourceURL(getBinaryDir());
}
protected URL getResourceURL(String resource) {
URL url =
Thread.currentThread().getContextClassLoader()
.getResource(resource);
if (url == null) {
throw new RuntimeException(
"Could not find resource with classloader: " + resource);
}
return url;
}
/**
* Load a file and return it as a <tt>byte[]</tt>. Useful for comparison
* operations in an actual unit test, e.g. to compare an imported database
* record against a known file state.
*
* @param filename
* the path of the file on the classpath, relative to configured
* <tt>binaryDir</tt> base path
* @return the file content as bytes
* @throws Exception
* when the file could not be found or read
*/
protected byte[] getBinaryFile(String filename) throws Exception {
if (getBinaryDir() == null) {
throw new RuntimeException(
"Please set binaryDir TestNG property to location of binary test files");
}
File file =
new File(getResourceURL(getBinaryDir() + "/" + filename)
.toURI());
InputStream is = new FileInputStream(file);
try {
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;
int numRead;
while (offset < bytes.length
&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "
+ file.getName());
}
return bytes;
} finally {
is.close();
}
}
/**
* Implement this in a subclass.
* <p/>
* Use it to stack DBUnit <tt>DataSetOperation</tt>'s with the
* <tt>beforeTestOperations</tt> and <tt>afterTestOperations</tt> lists.
*/
protected abstract void prepareDBUnitOperations();
}