https://kotlinlang.org logo
#kotest
Title
# kotest
p

Peter

12/09/2021, 6:33 PM
after upgrading from 4.6.3 to 5.0.1, integration tests are failing when using a postgres testcontainer + listener 🤔
Copy code
io.kotest.engine.extensions.ExtensionException$BeforeSpecException: java.lang.IllegalStateException: Mapped port can only be obtained after the container is started
      at app//io.kotest.engine.spec.SpecExtensions$beforeSpec$errors$1$2.invoke(SpecExtensions.kt:50)
      at app//io.kotest.engine.spec.SpecExtensions$beforeSpec$errors$1$2.invoke(SpecExtensions.kt:50)
      at app//io.kotest.common.ResultsKt.mapError(results.kt:8)
Copy code
class UserSpec: WordSpec() {
    private val network = Network.newNetwork()

    private val postgresContainer = PostgreSQLContainer(DockerImageName.parse("postgres:13"))
        .withDatabaseName(config.databaseConfig.databaseName)
        .withUsername(config.databaseConfig.username)
        .withPassword(config.databaseConfig.password.value)
        .withExposedPorts(5432)
        .withNetwork(network)

    init {
        listener(postgresContainer.perSpec())
......
    override fun beforeSpec(spec: Spec) {
        if (TestContainers.Postgres.logger.isDebugEnabled)
            postgresContainer.followOutput(Slf4jLogConsumer(TestContainers.Postgres.logger))
        val dataSource = ShutdownHookHikariDataSource.build(config.databaseConfig.copy(url = "jdbc:postgresql://${postgresContainer.containerIpAddress}:${postgresContainer.firstMappedPort}/${config.databaseConfig.databaseName}"))
        Flyway.configure().schemas(DefaultSchema).dataSource(dataSource).load().migrate()
        TransactionManager.defaultDatabase = Database.connect(dataSource)
    }
the container is starting, the listener doesn’t appear to wait for it
b

BorzdeG

12/09/2021, 6:40 PM
This is how it works for me:
Copy code
@SpringBootTest
internal class DatabaseStateIntegrationTest : FunSpec() {
	private val dbDockerDir = File("../docker/db-local")
	private val sqlInitDbDir = dbDockerDir.resolve("sql-initdb")
	private val entrypointInitDbDir = dbDockerDir.resolve("entrypoint-initdb")

	private val dbContainer = DatabaseContainer().apply {
		withFileSystemBind(sqlInitDbDir.absolutePath, "/opt/sql-initdb/", READ_ONLY)
		withFileSystemBind(entrypointInitDbDir.absolutePath, "/docker-entrypoint-initdb.d/", READ_ONLY)
		start()
	}

	override fun extensions() = listOf(SpringExtension)
	override fun listeners() = listOf(dbContainer.perSpec())

	init {
		beforeSpec {
			dbDockerDir.shouldNotBeEmptyDirectory()
			sqlInitDbDir.shouldBeADirectory()
			entrypointInitDbDir.shouldBeADirectory()
		}
// tests
	}

	class DatabaseContainer : PostgreSQLContainer<DatabaseContainer>("postgres:13.3") {
		override fun start() {
			super.start()
			System.setProperty("DB_USERNAME", username)
			System.setProperty("DB_PASSWORD", password)
			System.setProperty("DB_URL", jdbcUrl)
		}
	}
}
p

Peter

12/09/2021, 6:46 PM
thanks 🤔
5 Views