문제

I have an sbt project that has an integration test configuration defined. Build.scala:

  lazy val root =
    Project("root", file("."))
      .configs( IntegrationTest )
      .settings( Defaults.itSettings : _*)

build.sbt has (among other things):

    libraryDependencies ++=Seq(
      "org.scalatest" % "scala-test_2.10" % "1.0.8" % "test,it",
      "com.typesafe" % "config" % "1.2.0")

Now I have a reference.conf file under src/main/resources:

resources {
    postgresAdapter {
        db = "prod"
    }
}

and similarly under src/it/resources:

resources {
    postgresAdapter {
        db = "integration"
    }
}

I have a following class:

class PostgresAdapter{
  private val db = ConfigFactory.load.getConfig("resources").getString("postgresAdapter.db")

  private def connection: Try[java.sql.Connection] = {
    val _ = classOf[org.postgresql.Driver]
    Try(DriverManager.getConnection(s"jdbc:postgresql://dbserver/$db", "user", "password"))
  }
}

I want db to be initialized with prod if I do sbt run and initialized with integration when I do sbt it:test. Is it possible to configure sbt and/or Typesafe config to have this effect or should I use different means for that?

PS: I'd like to avoid having db_prod and db_integration parameters in a config file that goes to production.

도움이 되었습니까?

해결책

I think you could have an sbt problem (not getting your two folders on the classpath or not in the right order) or you could have a Typesafe Config problem (it isn't reading the two reference.conf which are on classpath).

Typesafe Config specifies the order it would load the two from the classpath: https://github.com/typesafehub/config/blob/master/HOCON.md#conventional-configuration-files-for-jvm-apps

You could do a klass.getClassLoader().getResources("reference.conf") to see what order your two reference.conf are showing up. If you have the src/it/resources one first, it should be overriding the src/main/resources one which I think is what you want?

If you don't have both reference.conf on the classpath, then you have an sbt problem (or at least, your first problem is sbt) and you need to get that extra folder on the classpath.

There are also other ways you could handle this with Typesafe Config, such as loading an extra resource if present like ConfigFactory.parseResources("testing.conf") and overriding settings with that, or forking your integration tests and setting system properties on the jvm command line like -Dresources.postgresAdapter.db ... I'm sure there are other creative solutions too, just depends on what you want.

I'll make this a wiki and if your problem turns out to be an sbt problem Eugene can probably fix you up!

(If Typesafe Config isn't working as specified please file a bug at https://github.com/typesafehub/config/issues )

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top