All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.producement.test.DockerContainerInitializer.kt Maven / Gradle / Ivy

package com.producement.test

import org.springframework.boot.test.util.TestPropertyValues
import org.springframework.context.ApplicationContextInitializer
import org.springframework.context.ConfigurableApplicationContext
import org.springframework.core.env.Profiles
import java.io.File
import java.nio.file.Path
import java.nio.file.Paths

class DockerContainerInitializer : ApplicationContextInitializer {

  companion object {
    private const val DB_PORT = 5432
    private val containers by lazy {
      KDockerComposeContainer(getDockerComposeFile(Paths.get(System.getProperty("user.dir"))))
        .withPull(false)
        .withEnv("DB_PORT", "")
        .withExposedService("db", 1, DB_PORT)
    }

    private fun getDockerComposeFile(dir: Path): File {
      val composeFile = dir.resolve("docker-compose.yml").toFile()
      if (composeFile.exists()) {
        return composeFile
      }
      return getDockerComposeFile(dir.parent)
    }
  }

  override fun initialize(applicationContext: ConfigurableApplicationContext) {
    if (!applicationContext.environment.acceptsProfiles(Profiles.of("ci"))) {
      containers.start()
      val dbHost = containers.getServiceHost("db", DB_PORT)
      val dbPort = containers.getServicePort("db", DB_PORT)
      TestPropertyValues.of(
        "spring.datasource.url=jdbc:postgresql://$dbHost:$dbPort/cleankitchen"
      ).applyTo(applicationContext.environment)
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy