-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPlayPostgresSpec.scala
66 lines (54 loc) · 2.6 KB
/
PlayPostgresSpec.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package controllers.common
import com.dimafeng.testcontainers.PostgreSQLContainer
import com.dimafeng.testcontainers.scalatest.TestContainerForEach
import net.wiringbits.spra.api.AdminDataExplorerApiClient
import org.scalatest.TestData
import org.scalatest.time.SpanSugar.convertIntToGrainOfTime
import org.scalatestplus.play.guice.GuiceOneServerPerTest
import org.testcontainers.utility.DockerImageName
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.{Application, Configuration, Environment, Mode}
import sttp.client3.SttpBackend
import scala.concurrent.{ExecutionContext, Future}
import scala.util.control.NonFatal
trait PlayPostgresSpec extends PlayAPISpec with TestContainerForEach with GuiceOneServerPerTest {
implicit val executionContext: ExecutionContext = ExecutionContext.Implicits.global
override implicit val patienceConfig: PatienceConfig = PatienceConfig(30.seconds, 1.second)
private val postgresImage = DockerImageName.parse("postgres:13")
override val containerDef: PostgreSQLContainer.Def = PostgreSQLContainer.Def(dockerImageName = postgresImage)
/** Loads configuration disabling evolutions on default database.
*
* This allows to not write a custom application.conf for testing and ensure play evolutions are disabled.
*/
private def loadConfigWithoutEvolutions(env: Environment, container: PostgreSQLContainer): Configuration = {
val map = Map(
"db.default.username" -> container.username,
"db.default.password" -> container.password,
"db.default.url" -> container.jdbcUrl
)
Configuration.from(map).withFallback(Configuration.load(env))
}
def guiceApplicationBuilder(container: PostgreSQLContainer): GuiceApplicationBuilder =
GuiceApplicationBuilder(loadConfiguration = env => loadConfigWithoutEvolutions(env, container))
.in(Mode.Test)
override def newAppForTest(testData: TestData): Application = {
withContainers { postgres =>
guiceApplicationBuilder(postgres).build()
}
}
def withApiClient[A](runTest: AdminDataExplorerApiClient => A): A = {
import sttp.client3.asynchttpclient.future.AsyncHttpClientFutureBackend
implicit val sttpBackend: SttpBackend[Future, Any] = AsyncHttpClientFutureBackend()
val config = AdminDataExplorerApiClient.Config(s"http://localhost:$port")
val client = new AdminDataExplorerApiClient.DefaultImpl(config)
runTest(client)
}
implicit class RichFutureExt[T](val future: Future[T]) {
def expectError: String = future
.map(_ => "Success when failure expected")
.recover { case NonFatal(ex) =>
ex.getMessage
}
.futureValue
}
}