Maciej Nawrocki
03/06/2024, 4:40 PMRaimund Klein
03/06/2024, 4:59 PM@ServiceConnection
annotation: https://www.baeldung.com/spring-boot-built-in-testcontainers#using-serviceconnection-for-dynamic-propertiesthanksforallthefish
03/08/2024, 7:57 AMclass ProjectConfig : AbstractProjectConfig() {
override fun extensions() = listOf(
ClearMockkExtension,
LocalstackExtension,
PostgresExtension,
KafkaExtension,
SpringExtension,
SpringAutowireConstructorExtension,
)
)
object PostgresExtension : ProjectExtension {
private val delegate = lazy {
PostgreSQLContainerProvider().newInstance("14.4")
.withNetwork(Network.SHARED)
.withNetworkAliases("db")
}
private val withNetworkAliases by delegate
override suspend fun interceptProject(context: ProjectContext, callback: suspend (ProjectContext) -> Unit) {
beforeProject()
callback(context)
afterProject()
}
private fun beforeProject() {
if (!withEnvVariables()) {
withNetworkAliases.start()
System.setProperty("spring.datasource.url", "jdbc:postgresql://${withNetworkAliases.connectionString()}")
System.setProperty("spring.datasource.username", withNetworkAliases.username)
System.setProperty("spring.datasource.password", withNetworkAliases.password)
System.setProperty("spring.flyway.schemas", withNetworkAliases.databaseName)
} else {
System.setProperty(
"spring.datasource.url",
"jdbc:postgresql://${System.getenv("POSTGRES_HOST")}:5432/${System.getenv("POSTGRES_DB")}"
)
System.setProperty("spring.datasource.username", System.getenv("POSTGRES_USER"))
System.setProperty("spring.datasource.password", System.getenv("POSTGRES_PASSWORD"))
System.setProperty("spring.flyway.schemas", System.getenv("POSTGRES_DB"))
}
}
private fun afterProject() {
if (delegate.isInitialized()) withNetworkAliases.stop()
}
private fun withEnvVariables() = System.getenv("POSTGRES_DB").isNotBlank()
private fun JdbcDatabaseContainer<*>.connectionString() = "$host:$firstMappedPort/$databaseName"
}