Project

General

Profile

Download (17 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2009 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9
package eu.etaxonomy.cdm.test.integration;
10

    
11
import java.io.FileNotFoundException;
12
import java.io.OutputStream;
13
import java.sql.SQLException;
14
import java.util.ArrayList;
15
import java.util.Collection;
16
import java.util.List;
17
import java.util.UUID;
18

    
19
import javax.sql.DataSource;
20
import javax.xml.transform.Source;
21
import javax.xml.transform.TransformerException;
22

    
23
import org.apache.logging.log4j.LogManager;
24
import org.apache.logging.log4j.Logger;
25
import org.dbunit.database.DatabaseConfig;
26
import org.dbunit.database.DatabaseConnection;
27
import org.dbunit.database.IDatabaseConnection;
28
import org.dbunit.dataset.filter.ITableFilterSimple;
29
import org.dbunit.dataset.xml.FlatXmlDataSet;
30
import org.dbunit.ext.h2.H2DataTypeFactory;
31
import org.h2.tools.Server;
32
import org.junit.Before;
33
import org.springframework.transaction.PlatformTransactionManager;
34
import org.springframework.transaction.support.DefaultTransactionDefinition;
35
import org.unitils.UnitilsJUnit4;
36
import org.unitils.database.annotations.TestDataSource;
37
import org.unitils.dbunit.util.MultiSchemaXmlDataSetReader;
38
import org.unitils.orm.hibernate.annotation.HibernateSessionFactory;
39
import org.unitils.spring.annotation.SpringApplicationContext;
40
import org.unitils.spring.annotation.SpringBeanByType;
41

    
42
import eu.etaxonomy.cdm.database.DataBaseTablePrinter;
43
import eu.etaxonomy.cdm.model.common.CdmBase;
44
import eu.etaxonomy.cdm.test.unitils.FlatFullXmlWriter;
45

    
46
/**
47
 * Abstract base class for integration testing a spring / hibernate application using
48
 * the unitils testing framework and dbunit.
49
 *
50
 * <h2>Data base server</h2>
51
 * The database being used is configured in
52
 * the maven module specific unitils.properties file. By default the database is a H2 in memory data base.
53
 * <p>
54
 * The H2 can be monitored during the test execution if the system property <code>h2Server</code> is given as
55
 * java virtual machine argument:
56
 * <code>-Dh2Server</code>.
57
 * An internal h2 database application will be started and listens at port 8082.
58
 * The port to listen on can be specified by passing a second argument, e.g.: <code>-Dh2Server 8083</code>.
59
 *
60
 * <h2>Creating create DbUnit dataset files</h2>
61
 * In order to create DbUnit datasets  for integration tests it is highly recommended method to use the
62
 * {@link #writeDbUnitDataSetFile(String[])} method.
63
 *
64
 * From {@link http://www.unitils.org/tutorial-database.html}, by default every test is executed in a transaction,
65
 * which is committed at the end of the test. This can be disabled using @Transactional(TransactionMode.DISABLED)
66
 *
67
 * @see <a href="http://www.unitils.org">unitils home page</a>
68
 *
69
 * @author ben.clark
70
 * @author a.kohlbecker (2013)
71
 */
72
@SpringApplicationContext("file:./target/test-classes/eu/etaxonomy/cdm/applicationContext-test.xml")
73
// @HibernateSessionFactory is only needed for test phases like afterTestTearDown
74
// which are configured to run without a spring application context.
75
// for further details, see /cdmlib-test/src/main/resources/eu/etaxonomy/cdm/hibernate-test.cfg.xml
76
@HibernateSessionFactory({"/eu/etaxonomy/cdm/hibernate.cfg.xml", "/eu/etaxonomy/cdm/hibernate-test.cfg.xml"})
77
public abstract class CdmIntegrationTest extends UnitilsJUnit4 {
78

    
79
    private static final Logger logger = LogManager.getLogger();
80

    
81
    private static final String PROPERTY_H2_SERVER = "h2Server";
82
    private static final String H2_SERVER_RUNNING = "h2ServerIsRunning";
83

    
84
    /**
85
     * List of the tables which are initially being populated during term loading. {@link PersistentTermInitializer}
86
     */
87
    public static final String[] termLoadingTables = new String[]{
88
        "DEFINEDTERMBASE",
89
        "DEFINEDTERMBASE_AUD",
90
        "DEFINEDTERMBASE_CONTINENT",
91
        "DEFINEDTERMBASE_REPRESENTATION",
92
        "DEFINEDTERMBASE_REPRESENTATION_AUD",
93
        "HIBERNATE_SEQUENCES",
94
        "TERMBASE_INVERSEREPRESENTATION",
95
        "TERMBASE_INVERSEREPRESENTATION_AUD",
96
        "REPRESENTATION",
97
        "REPRESENTATION_AUD",
98
        "TERMVOCABULARY",
99
        "TERMVOCABULARY_AUD",
100
        "TERMVOCABULARY_REPRESENTATION",
101
        "TERMVOCABULARY_REPRESENTATION_AUD"};
102

    
103
    @TestDataSource
104
    protected DataSource dataSource;
105

    
106
    private PlatformTransactionManager transactionManager;
107

    
108
    @SpringBeanByType
109
    private DataBaseTablePrinter dbTablePrinter;
110

    
111
    protected DefaultTransactionDefinition txDefinition = new DefaultTransactionDefinition();
112

    
113
    @SpringBeanByType
114
    public void setTransactionManager(PlatformTransactionManager transactionManager) {
115
        this.transactionManager = transactionManager;
116
    }
117

    
118

    
119
    protected IDatabaseConnection getConnection() {
120
        IDatabaseConnection connection = null;
121
        try {
122
            /// FIXME must use unitils.properties: database.schemaNames
123
            connection = new DatabaseConnection(dataSource.getConnection(), "PUBLIC");
124

    
125
            DatabaseConfig config = connection.getConfig();
126

    
127
            // FIXME must use unitils.properties: org.unitils.core.dbsupport.DbSupport.implClassName
128
            //       & database.dialect to find configured DataTypeFactory
129
            config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY,
130
                    new H2DataTypeFactory());
131
        } catch (Exception e) {
132
            logger.error(e);
133
        }
134
        return connection;
135
    }
136

    
137
    /**
138
     * How to use:
139
     * <ol>
140
     * <li>Add <code>-Dh2Server</code> as jvm argument to activate.</li>
141
     * <li>uncomment <code>database.url= jdbc:h2:tcp://localhost/~/cdm</code> in <code>/cdmlib-test/src/main/resources/unitils.properties</code></li>
142
     * @throws Exception
143
     */
144
    @Before
145
    public void startH2Server() throws Exception {
146

    
147
        if(System.getProperty(PROPERTY_H2_SERVER) != null && System.getProperty(H2_SERVER_RUNNING) == null){
148
            try {
149
                // printing to System.out, so that developers get feedback always
150
                System.out.println("####################################################");
151
                System.out.println("  Starting h2 web server ...");
152
                List<String> args = new ArrayList<>();
153
                Integer port = null;
154
                try {
155
                    port = Integer.parseInt(System.getProperty(PROPERTY_H2_SERVER));
156
                    args.add("-webPort");
157
                    args.add(port.toString());
158
                } catch (Exception e) {
159
                    // the default port is 8082
160
                }
161
                Server.createWebServer(args.toArray(new String[]{})).start();
162
                System.setProperty(H2_SERVER_RUNNING, "true");
163
                System.out.println("  you can connect to the h2 web server by opening");
164
                System.out.println("  http://localhost:" + (port != null ? port : "8082") + "/ in your browser");
165
                System.out.println("#####################################################");
166
            } catch (SQLException e) {
167
                e.printStackTrace();
168
            }
169
        }
170
    }
171

    
172

    
173
    /**
174
     * Prints the data set to an output stream, using the
175
     * {@link FlatXmlDataSet}.
176
     * <p>
177
     * Remember, if you've just called save() or
178
     * update(), the data isn't written to the database until the
179
     * transaction is committed, and that isn't until after the
180
     * method exits. Consequently, if you want to test writing to
181
     * the database, either use the {@literal @ExpectedDataSet}
182
     * annotation (that executes after the test is run), or use
183
     * {@link CdmTransactionalIntegrationTest}.
184
     *
185
     * @see {@link DataBaseTablePrinter}
186
     * @param out The OutputStream to write to.
187
     * @see FlatFullXmlWriter
188
     */
189
    public void printDataSet(OutputStream out) {
190
        dbTablePrinter.printDataSet(out);
191
    }
192

    
193
    /**
194
     * Prints the data set to an output stream, using the
195
     * {@link FlatFullXmlWriter}.
196
     * which is a variant of the {@link org.dbunit.dataset.xml.FlatXmlWriter}. It
197
     * inserts '[null]' place holders for null values instead of skipping them.
198
     * This was necessary for some time to make this xml database export compatible to the
199
     * {@link MultiSchemaXmlDataSetReader} which is used in unitils since version 3.x.
200
     * Newer versions of unitils handle <code>null</code> values correctly so this method
201
     * is now deprecated as explicitly mentioning <code>null</code> values litters the test
202
     * data and disturb during model updating.
203
     * <p>
204
     * @see {@link DataBaseTablePrinter}
205
     * @param out the OutputStream to write to.
206
     * @param includeTableNames
207
     * @deprecated use {@link #printDataSet(OutputStream, String...) as <code>null</code> values should not be mentioned in test data anymore
208
     *   (with very few where the null value is the value that is to be tested, these values
209
     *   should be added manually)
210
     */
211
    @Deprecated
212
    public void printDataSetWithNull(OutputStream out, String[] includeTableNames) {
213
        dbTablePrinter.printDataSetWithNull(out, includeTableNames);
214
    }
215

    
216
    /**
217
     * Prints the data set to an output stream, using the
218
     * {@link FlatFullXmlWriter}.
219
     * which is a variant of the {@link org.dbunit.dataset.xml.FlatXmlWriter}. It
220
     * inserts '[null]' place holders for null values instead of skipping them.
221
     * This was necessary for some time to make this xml database export compatible to the
222
     * {@link MultiSchemaXmlDataSetReader} which is used in unitils since version 3.x
223
     * but in the meanwhile handling of <code>null</code> values has been fixed in
224
     * unitils.
225
     * <p>
226
     * Remember, if you've just called save() or
227
     * update(), the data isn't written to the database until the
228
     * transaction is committed, and that isn't until after the
229
     * method exits. Consequently, if you want to test writing to
230
     * the database, either use the {@literal @ExpectedDataSet}
231
     * annotation (that executes after the test is run), or use
232
     * {@link CdmTransactionalIntegrationTest}.
233
     *
234
     * @see {@link DataBaseTablePrinter}
235
     * @param out The OutputStream to write to.
236
     * @see FlatFullXmlWriter
237
     * @deprecated use {@link #printDataSet(OutputStream)} instead, <code>null</code> values
238
     * litter the test data and disturb model updating and are not necessary anymore
239
     */
240
    @Deprecated
241
    public void printDataSetWithNull(OutputStream out) {
242
        dbTablePrinter.printDataSetWithNull(out);
243
    }
244

    
245
    /**
246
     * @param out
247
     * @param excludeTermLoadingTables
248
     * @param excludeFilter the tables to be <em>excluded</em>
249
     */
250
    public void printDataSet(OutputStream out, Boolean excludeTermLoadingTables,
251
            ITableFilterSimple excludeFilterOrig, String[] includeTableNames) {
252
        dbTablePrinter.printDataSet(out, excludeTermLoadingTables, excludeFilterOrig, includeTableNames, false);
253
    }
254

    
255
    /**
256
     * @param out
257
     * @param excludeTermLoadingTables
258
     * @param excludeFilter the tables to be <em>excluded</em>
259
     * @deprecated use {@link #printDataSet(OutputStream, Boolean, ITableFilterSimple, String[])
260
     *   instead, <code>null</code> values litter the test data and disturb model updating and are not necessary anymore
261
     */
262
    @Deprecated
263
    public void printDataSetWithNull(OutputStream out, Boolean excludeTermLoadingTables,
264
            ITableFilterSimple excludeFilterOrig, String[] includeTableNames) {
265
        dbTablePrinter.printDataSetWithNull(out, excludeTermLoadingTables, excludeFilterOrig, includeTableNames);
266
    }
267

    
268
    /**
269
     *
270
     * @param out
271
     * @param formatString can be null, otherwise a format string like eg. "&lt; %1$s /&gt;" see also {@link String#format(String, Object...)}
272
     */
273
    public void printTableNames(OutputStream out, String formatString) {
274
        dbTablePrinter.printTableNames(out, formatString);
275
    }
276

    
277
    /**
278
     * Prints the named tables to an output stream, using dbunit's
279
     * {@link org.dbunit.dataset.xml.FlatXmlDataSet}.
280
     * <p>
281
     * Remember, if you've just called save() or
282
     * update(), the data isn't written to the database until the
283
     * transaction is committed, and that isn't until after the
284
     * method exits. Consequently, if you want to test writing to
285
     * the database, either use the {@literal @ExpectedDataSet}
286
     * annotation (that executes after the test is run), or use
287
     * {@link CdmTransactionalIntegrationTest}.
288
     *
289
     * @see {@link DataBaseTablePrinter}
290
     *
291
     * @see {@link #printDataSet(OutputStream)}
292
     * @see FlatFullXmlWriter
293
     *
294
     * @param out
295
     * 		the OutputStream to write the XML to
296
     * @param includeTableNames
297
     * 		the names of tables to print (should be in upper case letters)
298
     */
299
    public void printDataSet(OutputStream out, String ... includeTableNames) {
300
        dbTablePrinter.printDataSet(out, includeTableNames);
301

    
302
    }
303

    
304
    /**
305
     * Prints the named tables to an output stream, using dbunit's
306
     * {@link org.dbunit.dataset.xml.FlatXmlWriter}.
307
     * <p>
308
     * Remember, if you've just called save() or
309
     * update(), the data isn't written to the database until the
310
     * transaction is committed, and that isn't until after the
311
     * method exits. Consequently, if you want to test writing to
312
     * the database, either use the {@literal @ExpectedDataSet}
313
     * annotation (that executes after the test is run), or use
314
     * {@link CdmTransactionalIntegrationTest}.
315
     *
316
     * @see {@link DataBaseTablePrinter}
317
     *
318
     * @see {@link #printDataSet(OutputStream)}
319
     * @see FlatFullXmlWriter
320
     * @param out
321
     * @param filter
322
     */
323
    public void printDataSet(OutputStream out, ITableFilterSimple filter) {
324
        dbTablePrinter.printDataSet(out, filter);
325
    }
326

    
327

    
328
    /**
329
     * Prints a dtd to an output stream, using dbunit's
330
     * {@link org.dbunit.dataset.xml.FlatDtdDataSet}.
331
     *
332
     * @param out The OutputStream to write to.
333
     * @see org.dbunit.dataset.xml.FlatDtdDataSet
334
     */
335
    public void printDtd(OutputStream out) {
336
        dbTablePrinter.printDtd(out);
337
    }
338

    
339
    /**
340
     * <b>WARNING</b> read this doc before using this method.
341
     * <p>
342
     * This is the recommended method to create DbUnit data set for integration tests.
343
     * This method will create the DbUnit data set file for the specific test class
344
     * it has been called from. This happens in full compliance with the DbUnit conventions,
345
     * so that the test class will immediately be able to use the
346
     * newly created file during the next run.
347
     * This also means that using <code>writeDbUnitDataSetFile()</code>
348
     * in a test class <b>will overwrite the existing data set file</b>. This is not
349
     * considered to be harmful since we expect that any development always is
350
     * backed up by a VCS like git, svn and therefore recovery of overwritten
351
     * data source files should not cause any problems.
352
     * <p>
353
     * Writes a  DbUnit dataset file from the current data base connection using the
354
     * {@link FlatFullXmlWriter} which is a variant of the
355
     * {@link org.dbunit.dataset.xml.FlatXmlWriter}. It
356
     * inserts <code>'[null]'</code> place holders for null values instead of skipping them.
357
     *
358
     * see {@link DataBaseTablePrinter}
359
     *
360
     * @param includeTableNames
361
     * @throws FileNotFoundException
362
     */
363
    public void writeDbUnitDataSetFile(String[] includeTableNames) throws FileNotFoundException {
364
        dbTablePrinter.writeDbUnitDataSetFile(includeTableNames, this.getClass());
365
    }
366

    
367
    /**
368
     *
369
     * Extension of method mentioned in "see also" where you can specify an appendix for the
370
     * generated DbUnit data set file.
371
     *
372
     * see {@link DataBaseTablePrinter}
373
     *
374
     * @param includeTableNames
375
     * @param fileAppendix the appendix of the generated DbUnit dataset file
376
     * @throws FileNotFoundException
377
     * @see #writeDbUnitDataSetFile(String[])
378
     */
379
    public void writeDbUnitDataSetFile(String[] includeTableNames, String fileAppendix, boolean withNullValues) throws FileNotFoundException {
380
        dbTablePrinter.writeDbUnitDataSetFile(includeTableNames, this.getClass(), fileAppendix, withNullValues);
381
    }
382

    
383
    /**
384
     * see {@link DataBaseTablePrinter#transformSourceToString(Source)
385
     */
386
    protected String transformSourceToString(Source source) throws TransformerException {
387
        return dbTablePrinter.transformSourceToString(source);
388
    }
389

    
390

    
391
    protected <T extends CdmBase> T getEntityFromCollection(Collection<T> cdmBases, UUID uuid) {
392
        for (T cdmBase : cdmBases){
393
            if (cdmBase.getUuid().equals(uuid)){
394
                return cdmBase;
395
            }
396
        }
397
        return null;
398
    }
399

    
400
    protected boolean existsInCollection(Collection<? extends CdmBase> cdmBases, UUID uuid) {
401
         return getEntityFromCollection(cdmBases, uuid) != null;
402
    }
403

    
404

    
405
    /**
406
     * This is the common method to create test data xml files for integration tests.
407
     *
408
     * With {@link CdmTransactionalIntegrationTestExample#createTestDataSet} an example
409
     * implementation of this method is provided.
410
     *
411
     * @throws FileNotFoundException
412
     */
413
    public abstract void createTestDataSet() throws FileNotFoundException;
414
}
(1-1/5)