forked from DSpace/DSpace
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAbstractIntegrationTestWithDatabase.java
More file actions
271 lines (243 loc) · 11.2 KB
/
Copy pathAbstractIntegrationTestWithDatabase.java
File metadata and controls
271 lines (243 loc) · 11.2 KB
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
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace;
import static org.junit.Assert.fail;
import java.sql.SQLException;
import java.util.ConcurrentModificationException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.dspace.app.launcher.ScriptLauncher;
import org.dspace.app.scripts.handler.impl.TestDSpaceRunnableHandler;
import org.dspace.authority.AuthoritySearchService;
import org.dspace.authority.MockAuthoritySolrServiceImpl;
import org.dspace.builder.AbstractBuilder;
import org.dspace.builder.EPersonBuilder;
import org.dspace.content.Community;
import org.dspace.core.Context;
import org.dspace.core.I18nUtil;
import org.dspace.discovery.MockSolrSearchCore;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.Group;
import org.dspace.eperson.factory.EPersonServiceFactory;
import org.dspace.eperson.service.EPersonService;
import org.dspace.eperson.service.GroupService;
import org.dspace.kernel.ServiceManager;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.dspace.statistics.MockSolrLoggerServiceImpl;
import org.dspace.statistics.MockSolrStatisticsCore;
import org.dspace.statistics.SolrStatisticsCore;
import org.dspace.storage.rdbms.DatabaseUtils;
import org.jdom2.Document;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
/**
* Abstract Test class that will initialize the in-memory database
*/
public class AbstractIntegrationTestWithDatabase extends AbstractDSpaceIntegrationTest {
/**
* log4j category
*/
private static final Logger log = LogManager
.getLogger(AbstractIntegrationTestWithDatabase.class);
/**
* Context mock object to use in the tests.
*/
protected Context context;
/**
* EPerson mock object to use in the tests.
*/
protected EPerson eperson;
/**
* EPerson mock object in the Administrators group to use in the tests.
*/
protected EPerson admin;
/**
* The password of our test eperson
*/
protected String password = "mySuperS3cretP4ssW0rd";
/**
* The test Parent Community
*/
protected Community parentCommunity = null;
/**
* This method will be run before the first test as per @BeforeClass. It will
* initialize shared resources required for all tests of this class.
* <p>
* NOTE: Per JUnit, "The @BeforeClass methods of superclasses will be run before those the current class."
* http://junit.org/apidocs/org/junit/BeforeClass.html
* <p>
* This method builds on the initialization in AbstractDSpaceIntegrationTest, and
* initializes the in-memory database for tests that need it.
*/
@BeforeClass
public static void initDatabase() {
try {
// Update/Initialize the database to latest version (via Flyway)
DatabaseUtils.updateDatabase();
} catch (SQLException se) {
log.error("Error initializing database", se);
fail("Error initializing database: " + se.getMessage()
+ (se.getCause() == null ? "" : ": " + se.getCause().getMessage()));
}
}
/**
* This method will be run before every test as per @Before. It will
* initialize resources required for each individual unit test.
*
* Other methods can be annotated with @Before here or in subclasses
* but no execution order is guaranteed
*/
@Before
public void setUp() throws Exception {
try {
//Start a new context
context = new Context(Context.Mode.READ_WRITE);
context.turnOffAuthorisationSystem();
//Find our global test EPerson account. If it doesn't exist, create it.
EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService();
eperson = ePersonService.findByEmail(context, "test@email.com");
if (eperson == null) {
// Create test EPerson for usage in all tests
log.info("Creating Test EPerson (email=test@email.com) for Integration Tests");
eperson = EPersonBuilder.createEPerson(context)
.withNameInMetadata("first", "last")
.withEmail("test@email.com")
.withCanLogin(true)
.withLanguage(I18nUtil.getDefaultLocale().getLanguage())
.withPassword(password)
.build();
}
// Set our global test EPerson as the current user in DSpace
context.setCurrentUser(eperson);
// If our Anonymous/Administrator groups aren't initialized, initialize them as well
EPersonServiceFactory.getInstance().getGroupService().initDefaultGroupNames(context);
admin = ePersonService.findByEmail(context, "admin@email.com");
if (admin == null) {
// Create test Administrator for usage in all tests
log.info("Creating Test Admin EPerson (email=admin@email.com) for Integration Tests");
admin = EPersonBuilder.createEPerson(context)
.withNameInMetadata("first (admin)", "last (admin)")
.withEmail("admin@email.com")
.withCanLogin(true)
.withLanguage(I18nUtil.getDefaultLocale().getLanguage())
.withPassword(password)
.build();
// Add Test Administrator to the ADMIN group in test database
GroupService groupService = EPersonServiceFactory.getInstance().getGroupService();
Group adminGroup = groupService.findByName(context, Group.ADMIN);
groupService.addMember(context, adminGroup, admin);
}
context.restoreAuthSystemState();
} catch (SQLException ex) {
log.error(ex.getMessage(), ex);
fail("SQL Error on AbstractUnitTest init()");
}
}
/**
* This method will be run after every test as per @After. It will
* clean resources initialized by the @Before methods.
*
* Other methods can be annotated with @After here or in subclasses
* but no execution order is guaranteed.
*
* @throws java.lang.Exception passed through.
*/
@After
public void destroy() throws Exception {
// Cleanup our global context object
try {
// Builders/cleanupContext can trigger a transactional commit through Hibernate.
// Older Hibernate releases have a race in ResourceRegistryStandardImpl#releaseResources
// where the close() callback removes the just-iterated entry from the registry map,
// causing an intermittent ConcurrentModificationException (see HHH-15116).
// The DB cleanup work is best-effort here (test data is purged per-class anyway),
// so on CME we abort the context to release the JDBC connection and continue
// with the remaining (Solr/config) cleanup instead of failing an already-passed test.
try {
AbstractBuilder.cleanupObjects();
parentCommunity = null;
cleanupContext();
} catch (ConcurrentModificationException cme) {
log.warn("Ignoring transient Hibernate CME during @After cleanup (HHH-15116); "
+ "aborting context and continuing.", cme);
if (context != null && context.isValid()) {
context.abort();
}
context = null;
parentCommunity = null;
}
ServiceManager serviceManager = DSpaceServicesFactory.getInstance().getServiceManager();
// Clear the search core.
MockSolrSearchCore searchService = serviceManager
.getServiceByName(null, MockSolrSearchCore.class);
searchService.reset();
// Clear the statistics core.
serviceManager
.getServiceByName(SolrStatisticsCore.class.getName(), MockSolrStatisticsCore.class)
.reset();
MockSolrLoggerServiceImpl statisticsService = serviceManager
.getServiceByName("solrLoggerService", MockSolrLoggerServiceImpl.class);
statisticsService.reset();
MockAuthoritySolrServiceImpl authorityService = serviceManager
.getServiceByName(AuthoritySearchService.class.getName(), MockAuthoritySolrServiceImpl.class);
authorityService.reset();
// Reload our ConfigurationService (to reset configs to defaults again)
DSpaceServicesFactory.getInstance().getConfigurationService().reloadConfig();
AbstractBuilder.cleanupBuilderCache();
// NOTE: we explicitly do NOT destroy our default eperson & admin as they
// are cached and reused for all tests. This speeds up all tests.
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Utility method to cleanup a created Context object (to save memory).
* This can also be used by individual tests to cleanup context objects they create.
* @throws java.sql.SQLException passed through.
*/
protected void cleanupContext() throws SQLException {
// If context still valid, flush all database changes and close it
if (context != null && context.isValid()) {
context.complete();
}
// Cleanup Context object by setting it to null
if (context != null) {
context = null;
}
}
/**
* Execute the given command and return the exit code.
*
* @param args the args to use for the script.
* @return the status, 0 if success, non-zero otherwise.
* @throws Exception if there's an error cleaning up after running the command.
*/
public int runDSpaceScript(String... args) throws Exception {
try {
// Load up the ScriptLauncher's configuration
Document commandConfigs = ScriptLauncher.getConfig(kernelImpl);
// Check that there is at least one argument (if not display command options)
if (args.length < 1) {
log.error("You must provide at least one command argument");
}
// Look up command in the configuration, and execute.
TestDSpaceRunnableHandler testDSpaceRunnableHandler = new TestDSpaceRunnableHandler();
int status = ScriptLauncher.handleScript(args, commandConfigs, testDSpaceRunnableHandler, kernelImpl);
if (testDSpaceRunnableHandler.getException() != null) {
throw testDSpaceRunnableHandler.getException();
} else {
return status;
}
} finally {
if (!context.isValid()) {
setUp();
}
}
}
}