Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove workaround for a bug in testcontainers #32

Merged
merged 1 commit into from
Jul 14, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,9 @@ import org.testcontainers.containers.JdbcDatabaseContainer
import org.testcontainers.containers.output.Slf4jLogConsumer
import org.testcontainers.containers.wait.strategy.HostPortWaitStrategy
import org.testcontainers.utility.DockerImageName
import java.lang.reflect.Field
import java.sql.Driver
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

class GenericDatabaseContainer(
private val image: Image,
Expand All @@ -21,11 +18,7 @@ class GenericDatabaseContainer(
) : JdbcDatabaseContainer<GenericDatabaseContainer>(DockerImageName.parse(image.name)) {

private val driverLoadLock = ReentrantLock()
private var driver: Driver? by ReflectionDelegate(
JdbcDatabaseContainer::class.java.getDeclaredField("driver").also {
it.isAccessible = true
}
)
private var driver: Driver? = null

init {
withLogConsumer(
Expand Down Expand Up @@ -55,29 +48,23 @@ class GenericDatabaseContainer(
if (driver == null) {
driverLoadLock.withLock {
if (driver == null) {
return try {
@Suppress("DEPRECATION")
jdbcAwareClassLoader.loadClass(driverClassName).newInstance() as Driver
} catch (e: Exception) {
when (e) {
is InstantiationException, is IllegalAccessException, is ClassNotFoundException -> {
throw NoDriverFoundException("Could not get Driver", e)
}
else -> throw e
}
}.also {
driver = it
}
driver = getNewJdbcDriverInstance()
}
}
}

return driver!!
}

private class ReflectionDelegate<T>(private val field: Field) : ReadWriteProperty<Any, T> {
@Suppress("UNCHECKED_CAST")
override fun getValue(thisRef: Any, property: KProperty<*>): T = field.get(thisRef) as T
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) = field.set(thisRef, value)
private fun getNewJdbcDriverInstance() = try {
@Suppress("DEPRECATION")
jdbcAwareClassLoader.loadClass(driverClassName).newInstance() as Driver
} catch (e: Exception) {
when (e) {
is InstantiationException, is IllegalAccessException, is ClassNotFoundException -> {
throw NoDriverFoundException("Could not get Driver", e)
}
else -> throw e
}
}
}