generated from DataONEorg/repo-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestUtils.java
More file actions
73 lines (64 loc) · 3.05 KB
/
TestUtils.java
File metadata and controls
73 lines (64 loc) · 3.05 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
package org.dataone.notifications.util;
import org.apache.commons.configuration2.Configuration;
import org.dataone.notifications.NsConfig;
import org.dataone.notifications.storage.DBConnectionParams;
import org.dataone.notifications.storage.DataRepository;
import org.dataone.notifications.storage.NsDBMigrator;
import org.dataone.notifications.storage.NsDataRepository;
import org.dataone.notifications.storage.NsDataSource;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.containers.wait.strategy.Wait;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.time.Duration;
public class TestUtils {
public static PostgreSQLContainer<?> getTestDb() {
Configuration nsConfig = NsConfig.getConfig();
PostgreSQLContainer<?> pg =
new PostgreSQLContainer<>("postgres:" + nsConfig.getString("ns.database.test.version"))
.withDatabaseName(nsConfig.getString("ns.database.name"))
.withUsername(nsConfig.getString("ns.database.username"))
.withPassword(nsConfig.getString("ns.database.password"))
.waitingFor(Wait.forListeningPort().withStartupTimeout(Duration.ofMinutes(1)))
.waitingFor(
Wait.forLogMessage(".*database system is ready to accept connections.*", 1));
pg.start();
verifyPostgresPortAvailable(pg);
return pg;
}
public static synchronized DataRepository getTestDataRepository(PostgreSQLContainer<?> pg) {
final DBConnectionParams dbConnectionParams =
new DBConnectionParams(pg.getJdbcUrl(), pg.getDriverClassName(), pg.getUsername(),
pg.getPassword());
final NsDataSource dataSource = new NsDataSource(dbConnectionParams);
final NsDBMigrator migrator = new NsDBMigrator(dataSource);
return new NsDataRepository(dataSource, migrator);
}
private static void verifyPostgresPortAvailable(PostgreSQLContainer<?> pg) {
// retries here
int retries = 30;
int retryCount = retries;
int delayMs = 200;
int mappedPort = pg.getMappedPort(5432);
while (retryCount-- > 0) {
try (Socket socket = new Socket()) {
socket.connect(
new InetSocketAddress(pg.getHost(), mappedPort), delayMs);
break; // success
} catch (IOException e) {
if (retryCount == 0) {
throw new RuntimeException("PostgreSQL port " + mappedPort
+ " not available on container startup after "
+ (retries * delayMs) + " ms.");
}
try {
Thread.sleep(delayMs);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted while waiting for PostgreSQL port", ie);
}
}
}
}
}