Project

General

Profile

Download (17.3 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.log4j.Logger;
24
import org.dbunit.database.DatabaseConfig;
25
import org.dbunit.database.DatabaseConnection;
26
import org.dbunit.database.IDatabaseConnection;
27
import org.dbunit.dataset.filter.ITableFilterSimple;
28
import org.dbunit.dataset.xml.FlatXmlDataSet;
29
import org.dbunit.ext.h2.H2DataTypeFactory;
30
import org.h2.tools.Server;
31
import org.junit.Before;
32
import org.springframework.transaction.PlatformTransactionManager;
33
import org.springframework.transaction.support.DefaultTransactionDefinition;
34
import org.unitils.UnitilsJUnit4;
35
import org.unitils.database.annotations.TestDataSource;
36
import org.unitils.dbunit.util.MultiSchemaXmlDataSetReader;
37
import org.unitils.orm.hibernate.annotation.HibernateSessionFactory;
38
import org.unitils.spring.annotation.SpringApplicationContext;
39
import org.unitils.spring.annotation.SpringBeanByType;
40

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

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

    
78
    protected static final Logger logger = Logger.getLogger(CdmIntegrationTest.class);
79

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

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

    
102
    @TestDataSource
103
    protected DataSource dataSource;
104

    
105
    private PlatformTransactionManager transactionManager;
106

    
107
    @SpringBeanByType
108
    private DataBaseTablePrinter dbTablePrinter;
109

    
110
    protected DefaultTransactionDefinition txDefinition = new DefaultTransactionDefinition();
111

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

    
117

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

    
124
            DatabaseConfig config = connection.getConfig();
125

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

    
136
//  @SpringBeanByType
137
//  private IAgentDao agentDao;
138
//
139
//  @Before
140
//  public void debugExistingUsers(){
141
//      StringBuilder agentstr = new StringBuilder();
142
//      for(AgentBase agent : agentDao.list(null, null)) {
143
//          agentstr.append(agent.getId()).append(", ");
144
//      }
145
//      System.err.println("####" +  agentstr);
146
//  }
147

    
148
    /**
149
     * How to use:
150
     * <ol>
151
     * <li>Add <code>-Dh2Server</code> as jvm argument to activate.</li>
152
     * <li>uncomment <code>database.url= jdbc:h2:tcp://localhost/~/cdm</code> in <code>/cdmlib-test/src/main/resources/unitils.properties</code></li>
153
     * @throws Exception
154
     */
155
    @Before
156
    public void startH2Server() throws Exception {
157

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

    
183

    
184
    /**
185
     * Prints the data set to an output stream, using the
186
     * {@link FlatXmlDataSet}.
187
     * <p>
188
     * Remember, if you've just called save() or
189
     * update(), the data isn't written to the database until the
190
     * transaction is committed, and that isn't until after the
191
     * method exits. Consequently, if you want to test writing to
192
     * the database, either use the {@literal @ExpectedDataSet}
193
     * annotation (that executes after the test is run), or use
194
     * {@link CdmTransactionalIntegrationTest}.
195
     *
196
     * @see {@link DataBaseTablePrinter}
197
     * @param out The OutputStream to write to.
198
     * @see FlatFullXmlWriter
199
     */
200
    public void printDataSet(OutputStream out) {
201
        dbTablePrinter.printDataSet(out);
202
    }
203

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

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

    
256
    /**
257
     * @param out
258
     * @param excludeTermLoadingTables
259
     * @param excludeFilter the tables to be <em>excluded</em>
260
     */
261
    public void printDataSet(OutputStream out, Boolean excludeTermLoadingTables,
262
            ITableFilterSimple excludeFilterOrig, String[] includeTableNames) {
263
        dbTablePrinter.printDataSet(out, excludeTermLoadingTables, excludeFilterOrig, includeTableNames, false);
264
    }
265

    
266
    /**
267
     * @param out
268
     * @param excludeTermLoadingTables
269
     * @param excludeFilter the tables to be <em>excluded</em>
270
     * @deprecated use {@link #printDataSet(OutputStream, Boolean, ITableFilterSimple, String[])
271
     *   instead, <code>null</code> values litter the test data and disturb model updating and are not necessary anymore
272
     */
273
    @Deprecated
274
    public void printDataSetWithNull(OutputStream out, Boolean excludeTermLoadingTables,
275
            ITableFilterSimple excludeFilterOrig, String[] includeTableNames) {
276
        dbTablePrinter.printDataSetWithNull(out, excludeTermLoadingTables, excludeFilterOrig, includeTableNames);
277
    }
278

    
279
    /**
280
     *
281
     * @param out
282
     * @param formatString can be null, otherwise a format string like eg. "&lt; %1$s /&gt;" see also {@link String#format(String, Object...)}
283
     */
284
    public void printTableNames(OutputStream out, String formatString) {
285
        dbTablePrinter.printTableNames(out, formatString);
286
    }
287

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

    
313
    }
314

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

    
338

    
339
    /**
340
     * Prints a dtd to an output stream, using dbunit's
341
     * {@link org.dbunit.dataset.xml.FlatDtdDataSet}.
342
     *
343
     * @param out The OutputStream to write to.
344
     * @see org.dbunit.dataset.xml.FlatDtdDataSet
345
     */
346
    public void printDtd(OutputStream out) {
347
        dbTablePrinter.printDtd(out);
348
    }
349

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

    
378
    /**
379
     *
380
     * Extension of method mentioned in "see also" where you can specify an appendix for the
381
     * generated DbUnit data set file.
382
     *
383
     * see {@link DataBaseTablePrinter}
384
     *
385
     * @param includeTableNames
386
     * @param fileAppendix the appendix of the generated DbUnit dataset file
387
     * @throws FileNotFoundException
388
     * @see #writeDbUnitDataSetFile(String[])
389
     */
390
    public void writeDbUnitDataSetFile(String[] includeTableNames, String fileAppendix, boolean withNullValues) throws FileNotFoundException {
391
        dbTablePrinter.writeDbUnitDataSetFile(includeTableNames, this.getClass(), fileAppendix, withNullValues);
392
    }
393

    
394
    /**
395
     * see {@link DataBaseTablePrinter#transformSourceToString(Source)
396
     */
397
    protected String transformSourceToString(Source source) throws TransformerException {
398
        return dbTablePrinter.transformSourceToString(source);
399
    }
400

    
401

    
402
    protected <T extends CdmBase> T getEntityFromCollection(Collection<T> cdmBases, UUID uuid) {
403
        for (T cdmBase : cdmBases){
404
            if (cdmBase.getUuid().equals(uuid)){
405
                return cdmBase;
406
            }
407
        }
408
        return null;
409
    }
410

    
411
    protected boolean existsInCollection(Collection<? extends CdmBase> cdmBases, UUID uuid) {
412
         return getEntityFromCollection(cdmBases, uuid) != null;
413
    }
414

    
415

    
416
    /**
417
     * This is the common method to create test data xml files for integration tests.
418
     *
419
     * With {@link CdmTransactionalIntegrationTestExample#createTestDataSet} an example
420
     * implementation of this method is provided.
421
     *
422
     * @throws FileNotFoundException
423
     */
424
    public abstract void createTestDataSet() throws FileNotFoundException;
425
}
(1-1/6)